2 * Tools for inspecting page composition and performance.
10 function sortByProperty( array, prop, descending ) {
11 var order = descending ? -1 : 1;
12 return array.sort( function ( a, b ) {
13 return a[prop] > b[prop] ? order : a[prop] < b[prop] ? -order : 0;
17 function humanSize( bytes ) {
18 if ( !$.isNumeric( bytes ) || bytes === 0 ) { return bytes; }
19 var i = 0, units = [ '', ' kB', ' MB', ' GB', ' TB', ' PB' ];
20 for ( ; bytes >= 1024; bytes /= 1024 ) { i++; }
21 return bytes.toFixed( 1 ) + units[i];
31 * Return a map of all dependency relationships between loaded modules.
33 * @return {Object} Maps module names to objects. Each sub-object has
34 * two properties, 'requires' and 'requiredBy'.
36 getDependencyGraph: function () {
37 var modules = inspect.getLoadedModules(), graph = {};
39 $.each( modules, function ( moduleIndex, moduleName ) {
40 var dependencies = mw.loader.moduleRegistry[moduleName].dependencies || [];
42 graph[moduleName] = graph[moduleName] || { requiredBy: [] };
43 graph[moduleName].requires = dependencies;
45 $.each( dependencies, function ( depIndex, depName ) {
46 graph[depName] = graph[depName] || { requiredBy: [] };
47 graph[depName].requiredBy.push( moduleName );
54 * Calculate the byte size of a ResourceLoader module.
56 * @param {string} moduleName The name of the module
57 * @return {number|null} Module size in bytes or null
59 getModuleSize: function ( moduleName ) {
60 var module = mw.loader.moduleRegistry[ moduleName ],
63 if ( mw.loader.getState( moduleName ) !== 'ready' ) {
67 if ( !module.style && !module.script ) {
72 if ( module.style && $.isArray( module.style.css ) ) {
73 $.each( module.style.css, function ( i, stylesheet ) {
74 payload += $.byteLength( stylesheet );
79 if ( $.isFunction( module.script ) ) {
80 payload += $.byteLength( module.script.toString() );
87 * Given CSS source, count both the total number of selectors it
88 * contains and the number which match some element in the current
91 * @param {string} css CSS source
92 * @return Selector counts
93 * @return {number} return.selectors Total number of selectors
94 * @return {number} return.matched Number of matched selectors
96 auditSelectors: function ( css ) {
97 var selectors = { total: 0, matched: 0 },
98 style = document.createElement( 'style' ),
101 style.textContent = css;
102 document.body.appendChild( style );
103 // Standards-compliant browsers use .sheet.cssRules, IE8 uses .styleSheet.rules…
104 sheet = style.sheet || style.styleSheet;
105 rules = sheet.cssRules || sheet.rules;
106 $.each( rules, function ( index, rule ) {
108 if ( document.querySelector( rule.selectorText ) !== null ) {
112 document.body.removeChild( style );
117 * Get a list of all loaded ResourceLoader modules.
119 * @return {Array} List of module names
121 getLoadedModules: function () {
122 return $.grep( mw.loader.getModuleNames(), function ( module ) {
123 return mw.loader.getState( module ) === 'ready';
128 * Print tabular data to the console, using console.table, console.log,
129 * or mw.log (in declining order of preference).
131 * @param {Array} data Tabular data represented as an array of objects
132 * with common properties.
134 dumpTable: function ( data ) {
136 // Bartosz made me put this here.
137 if ( window.opera ) { throw window.opera; }
138 // Use Function.prototype#call to force an exception on Firefox,
139 // which doesn't define console#table but doesn't complain if you
141 console.table.call( console, data );
145 console.log( JSON.stringify( data, null, 2 ) );
152 * Generate and print one more reports. When invoked with no arguments,
155 * @param {string...} [reports] Report names to run, or unset to print
156 * all available reports.
158 runReports: function () {
159 var reports = arguments.length > 0 ?
160 Array.prototype.slice.call( arguments ) :
161 $.map( inspect.reports, function ( v, k ) { return k; } );
163 $.each( reports, function ( index, name ) {
164 inspect.dumpTable( inspect.reports[name]() );
169 * @class mw.inspect.reports
174 * Generate a breakdown of all loaded modules and their size in
175 * kilobytes. Modules are ordered from largest to smallest.
178 // Map each module to a descriptor object.
179 var modules = $.map( inspect.getLoadedModules(), function ( module ) {
182 size: inspect.getModuleSize( module )
186 // Sort module descriptors by size, largest first.
187 sortByProperty( modules, 'size', true );
189 // Convert size to human-readable string.
190 $.each( modules, function ( i, module ) {
191 module.size = humanSize( module.size );
198 * For each module with styles, count the number of selectors, and
199 * count how many match against some element currently in the DOM.
204 $.each( inspect.getLoadedModules(), function ( index, name ) {
205 var css, stats, module = mw.loader.moduleRegistry[name];
208 css = module.style.css.join();
209 } catch ( e ) { return; } // skip
211 stats = inspect.auditSelectors( css );
214 allSelectors: stats.total,
215 matchedSelectors: stats.matched,
216 percentMatched: stats.total !== 0 ?
217 ( stats.matched / stats.total * 100 ).toFixed( 2 ) + '%' : null
220 sortByProperty( modules, 'allSelectors', true );
225 * Report stats on mw.loader.store: the number of localStorage
226 * cache hits and misses, the number of items purged from the
227 * cache, and the total size of the module blob in localStorage.
230 var raw, stats = { enabled: mw.loader.store.enabled };
231 if ( stats.enabled ) {
232 $.extend( stats, mw.loader.store.stats );
234 raw = localStorage.getItem( mw.loader.store.getStoreKey() );
235 stats.totalSize = humanSize( $.byteLength( raw ) );
243 * Perform a substring search across the JavaScript and CSS source code
244 * of all loaded modules and return an array of the names of the
245 * modules that matched.
247 * @param {string|RegExp} pattern String or regexp to match.
248 * @return {Array} Array of the names of modules that matched.
250 grep: function ( pattern ) {
251 if ( typeof pattern.test !== 'function' ) {
252 // Based on Y.Escape.regex from YUI v3.15.0
253 pattern = new RegExp( pattern.replace( /[\-$\^*()+\[\]{}|\\,.?\s]/g, '\\$&' ), 'g' );
256 return $.grep( inspect.getLoadedModules(), function ( moduleName ) {
257 var module = mw.loader.moduleRegistry[moduleName];
259 // Grep module's JavaScript
260 if ( $.isFunction( module.script ) && pattern.test( module.script.toString() ) ) {
266 $.isPlainObject( module.style ) && $.isArray( module.style.css )
267 && pattern.test( module.style.css.join( '' ) )
269 // Module's CSS source matches
278 if ( mw.config.get( 'debug' ) ) {
279 mw.log( 'mw.inspect: reports are not available in debug mode.' );
282 mw.inspect = inspect;
284 }( mediaWiki, jQuery ) );