Merge "mediawiki.inspect: Guard against Object.prototype keys as module names"
[lhc/web/wiklou.git] / resources / src / mediawiki / mediawiki.inspect.js
1 /*!
2 * Tools for inspecting page composition and performance.
3 *
4 * @author Ori Livneh
5 * @since 1.22
6 */
7 /*jshint devel:true */
8 ( function ( mw, $ ) {
9
10 var inspect,
11 hasOwn = Object.prototype.hasOwnProperty;
12
13 function sortByProperty( array, prop, descending ) {
14 var order = descending ? -1 : 1;
15 return array.sort( function ( a, b ) {
16 return a[prop] > b[prop] ? order : a[prop] < b[prop] ? -order : 0;
17 } );
18 }
19
20 function humanSize( bytes ) {
21 if ( !$.isNumeric( bytes ) || bytes === 0 ) { return bytes; }
22 var i = 0, units = [ '', ' kB', ' MB', ' GB', ' TB', ' PB' ];
23 for ( ; bytes >= 1024; bytes /= 1024 ) { i++; }
24 return bytes.toFixed( 1 ) + units[i];
25 }
26
27 /**
28 * @class mw.inspect
29 * @singleton
30 */
31 inspect = {
32
33 /**
34 * Return a map of all dependency relationships between loaded modules.
35 *
36 * @return {Object} Maps module names to objects. Each sub-object has
37 * two properties, 'requires' and 'requiredBy'.
38 */
39 getDependencyGraph: function () {
40 var modules = inspect.getLoadedModules(), graph = {};
41
42 $.each( modules, function ( moduleIndex, moduleName ) {
43 var dependencies = mw.loader.moduleRegistry[moduleName].dependencies || [];
44
45 if ( !hasOwn.call( graph, moduleName ) ) {
46 graph[moduleName] = { requiredBy: [] };
47 }
48 graph[moduleName].requires = dependencies;
49
50 $.each( dependencies, function ( depIndex, depName ) {
51 if ( !hasOwn.call( graph, depName ) ) {
52 graph[depName] = { requiredBy: [] };
53 }
54 graph[depName].requiredBy.push( moduleName );
55 } );
56 } );
57 return graph;
58 },
59
60 /**
61 * Calculate the byte size of a ResourceLoader module.
62 *
63 * @param {string} moduleName The name of the module
64 * @return {number|null} Module size in bytes or null
65 */
66 getModuleSize: function ( moduleName ) {
67 var module = mw.loader.moduleRegistry[ moduleName ],
68 payload = 0;
69
70 if ( mw.loader.getState( moduleName ) !== 'ready' ) {
71 return null;
72 }
73
74 if ( !module.style && !module.script ) {
75 return null;
76 }
77
78 // Tally CSS
79 if ( module.style && $.isArray( module.style.css ) ) {
80 $.each( module.style.css, function ( i, stylesheet ) {
81 payload += $.byteLength( stylesheet );
82 } );
83 }
84
85 // Tally JavaScript
86 if ( $.isFunction( module.script ) ) {
87 payload += $.byteLength( module.script.toString() );
88 }
89
90 return payload;
91 },
92
93 /**
94 * Given CSS source, count both the total number of selectors it
95 * contains and the number which match some element in the current
96 * document.
97 *
98 * @param {string} css CSS source
99 * @return Selector counts
100 * @return {number} return.selectors Total number of selectors
101 * @return {number} return.matched Number of matched selectors
102 */
103 auditSelectors: function ( css ) {
104 var selectors = { total: 0, matched: 0 },
105 style = document.createElement( 'style' ),
106 sheet, rules;
107
108 style.textContent = css;
109 document.body.appendChild( style );
110 // Standards-compliant browsers use .sheet.cssRules, IE8 uses .styleSheet.rules…
111 sheet = style.sheet || style.styleSheet;
112 rules = sheet.cssRules || sheet.rules;
113 $.each( rules, function ( index, rule ) {
114 selectors.total++;
115 if ( document.querySelector( rule.selectorText ) !== null ) {
116 selectors.matched++;
117 }
118 } );
119 document.body.removeChild( style );
120 return selectors;
121 },
122
123 /**
124 * Get a list of all loaded ResourceLoader modules.
125 *
126 * @return {Array} List of module names
127 */
128 getLoadedModules: function () {
129 return $.grep( mw.loader.getModuleNames(), function ( module ) {
130 return mw.loader.getState( module ) === 'ready';
131 } );
132 },
133
134 /**
135 * Print tabular data to the console, using console.table, console.log,
136 * or mw.log (in declining order of preference).
137 *
138 * @param {Array} data Tabular data represented as an array of objects
139 * with common properties.
140 */
141 dumpTable: function ( data ) {
142 try {
143 // Bartosz made me put this here.
144 if ( window.opera ) { throw window.opera; }
145 // Use Function.prototype#call to force an exception on Firefox,
146 // which doesn't define console#table but doesn't complain if you
147 // try to invoke it.
148 console.table.call( console, data );
149 return;
150 } catch ( e ) {}
151 try {
152 console.log( JSON.stringify( data, null, 2 ) );
153 return;
154 } catch ( e ) {}
155 mw.log( data );
156 },
157
158 /**
159 * Generate and print one more reports. When invoked with no arguments,
160 * print all reports.
161 *
162 * @param {string...} [reports] Report names to run, or unset to print
163 * all available reports.
164 */
165 runReports: function () {
166 var reports = arguments.length > 0 ?
167 Array.prototype.slice.call( arguments ) :
168 $.map( inspect.reports, function ( v, k ) { return k; } );
169
170 $.each( reports, function ( index, name ) {
171 inspect.dumpTable( inspect.reports[name]() );
172 } );
173 },
174
175 /**
176 * @class mw.inspect.reports
177 * @singleton
178 */
179 reports: {
180 /**
181 * Generate a breakdown of all loaded modules and their size in
182 * kilobytes. Modules are ordered from largest to smallest.
183 */
184 size: function () {
185 // Map each module to a descriptor object.
186 var modules = $.map( inspect.getLoadedModules(), function ( module ) {
187 return {
188 name: module,
189 size: inspect.getModuleSize( module )
190 };
191 } );
192
193 // Sort module descriptors by size, largest first.
194 sortByProperty( modules, 'size', true );
195
196 // Convert size to human-readable string.
197 $.each( modules, function ( i, module ) {
198 module.size = humanSize( module.size );
199 } );
200
201 return modules;
202 },
203
204 /**
205 * For each module with styles, count the number of selectors, and
206 * count how many match against some element currently in the DOM.
207 */
208 css: function () {
209 var modules = [];
210
211 $.each( inspect.getLoadedModules(), function ( index, name ) {
212 var css, stats, module = mw.loader.moduleRegistry[name];
213
214 try {
215 css = module.style.css.join();
216 } catch ( e ) { return; } // skip
217
218 stats = inspect.auditSelectors( css );
219 modules.push( {
220 module: name,
221 allSelectors: stats.total,
222 matchedSelectors: stats.matched,
223 percentMatched: stats.total !== 0 ?
224 ( stats.matched / stats.total * 100 ).toFixed( 2 ) + '%' : null
225 } );
226 } );
227 sortByProperty( modules, 'allSelectors', true );
228 return modules;
229 },
230
231 /**
232 * Report stats on mw.loader.store: the number of localStorage
233 * cache hits and misses, the number of items purged from the
234 * cache, and the total size of the module blob in localStorage.
235 */
236 store: function () {
237 var raw, stats = { enabled: mw.loader.store.enabled };
238 if ( stats.enabled ) {
239 $.extend( stats, mw.loader.store.stats );
240 try {
241 raw = localStorage.getItem( mw.loader.store.getStoreKey() );
242 stats.totalSize = humanSize( $.byteLength( raw ) );
243 } catch ( e ) {}
244 }
245 return [stats];
246 }
247 },
248
249 /**
250 * Perform a string search across the JavaScript and CSS source code
251 * of all loaded modules and return an array of the names of the
252 * modules that matched.
253 *
254 * @param {string|RegExp} pattern String or regexp to match.
255 * @return {Array} Array of the names of modules that matched.
256 */
257 grep: function ( pattern ) {
258 if ( typeof pattern.test !== 'function' ) {
259 // Based on Y.Escape.regex from YUI v3.15.0
260 pattern = new RegExp( pattern.replace( /[\-$\^*()+\[\]{}|\\,.?\s]/g, '\\$&' ), 'g' );
261 }
262
263 return $.grep( inspect.getLoadedModules(), function ( moduleName ) {
264 var module = mw.loader.moduleRegistry[moduleName];
265
266 // Grep module's JavaScript
267 if ( $.isFunction( module.script ) && pattern.test( module.script.toString() ) ) {
268 return true;
269 }
270
271 // Grep module's CSS
272 if (
273 $.isPlainObject( module.style ) && $.isArray( module.style.css )
274 && pattern.test( module.style.css.join( '' ) )
275 ) {
276 // Module's CSS source matches
277 return true;
278 }
279
280 return false;
281 } );
282 }
283 };
284
285 if ( mw.config.get( 'debug' ) ) {
286 mw.log( 'mw.inspect: reports are not available in debug mode.' );
287 }
288
289 mw.inspect = inspect;
290
291 }( mediaWiki, jQuery ) );