2 * Tools for inspecting page composition and performance.
11 hasOwn = Object.prototype.hasOwnProperty;
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;
20 function humanSize( bytes ) {
21 if ( !$.isNumeric( bytes ) || bytes === 0 ) { return bytes; }
23 units = [ '', ' kB', ' MB', ' GB', ' TB', ' PB' ];
25 for ( ; bytes >= 1024; bytes /= 1024 ) { i++; }
26 // Maintain one decimal for kB and above, but don't
27 // add ".0" for bytes.
28 return bytes.toFixed( i > 0 ? 1 : 0 ) + units[ i ];
38 * Return a map of all dependency relationships between loaded modules.
40 * @return {Object} Maps module names to objects. Each sub-object has
41 * two properties, 'requires' and 'requiredBy'.
43 getDependencyGraph: function () {
44 var modules = inspect.getLoadedModules(),
47 $.each( modules, function ( moduleIndex, moduleName ) {
48 var dependencies = mw.loader.moduleRegistry[ moduleName ].dependencies || [];
50 if ( !hasOwn.call( graph, moduleName ) ) {
51 graph[ moduleName ] = { requiredBy: [] };
53 graph[ moduleName ].requires = dependencies;
55 $.each( dependencies, function ( depIndex, depName ) {
56 if ( !hasOwn.call( graph, depName ) ) {
57 graph[ depName ] = { requiredBy: [] };
59 graph[ depName ].requiredBy.push( moduleName );
66 * Calculate the byte size of a ResourceLoader module.
68 * @param {string} moduleName The name of the module
69 * @return {number|null} Module size in bytes or null
71 getModuleSize: function ( moduleName ) {
72 var module = mw.loader.moduleRegistry[ moduleName ],
75 if ( mw.loader.getState( moduleName ) !== 'ready' ) {
79 if ( !module.style && !module.script ) {
84 if ( module.style && $.isArray( module.style.css ) ) {
85 $.each( module.style.css, function ( i, stylesheet ) {
86 payload += $.byteLength( stylesheet );
91 if ( $.isFunction( module.script ) ) {
92 payload += $.byteLength( module.script.toString() );
99 * Given CSS source, count both the total number of selectors it
100 * contains and the number which match some element in the current
103 * @param {string} css CSS source
104 * @return {Object} Selector counts
105 * @return {number} return.selectors Total number of selectors
106 * @return {number} return.matched Number of matched selectors
108 auditSelectors: function ( css ) {
109 var selectors = { total: 0, matched: 0 },
110 style = document.createElement( 'style' ),
113 style.textContent = css;
114 document.body.appendChild( style );
115 // Standards-compliant browsers use .sheet.cssRules, IE8 uses .styleSheet.rules…
116 sheet = style.sheet || style.styleSheet;
117 rules = sheet.cssRules || sheet.rules;
118 $.each( rules, function ( index, rule ) {
120 // document.querySelector() on prefixed pseudo-elements can throw exceptions
121 // in Firefox and Safari. Ignore these exceptions.
122 // https://bugs.webkit.org/show_bug.cgi?id=149160
123 // https://bugzilla.mozilla.org/show_bug.cgi?id=1204880
125 if ( document.querySelector( rule.selectorText ) !== null ) {
130 document.body.removeChild( style );
135 * Get a list of all loaded ResourceLoader modules.
137 * @return {Array} List of module names
139 getLoadedModules: function () {
140 return $.grep( mw.loader.getModuleNames(), function ( module ) {
141 return mw.loader.getState( module ) === 'ready';
146 * Print tabular data to the console, using console.table, console.log,
147 * or mw.log (in declining order of preference).
149 * @param {Array} data Tabular data represented as an array of objects
150 * with common properties.
152 dumpTable: function ( data ) {
154 // Bartosz made me put this here.
155 if ( window.opera ) { throw window.opera; }
156 // Use Function.prototype#call to force an exception on Firefox,
157 // which doesn't define console#table but doesn't complain if you
159 console.table.call( console, data );
163 console.log( JSON.stringify( data, null, 2 ) );
170 * Generate and print one more reports. When invoked with no arguments,
173 * @param {...string} [reports] Report names to run, or unset to print
174 * all available reports.
176 runReports: function () {
177 var reports = arguments.length > 0 ?
178 Array.prototype.slice.call( arguments ) :
179 $.map( inspect.reports, function ( v, k ) { return k; } );
181 $.each( reports, function ( index, name ) {
182 inspect.dumpTable( inspect.reports[ name ]() );
187 * @class mw.inspect.reports
192 * Generate a breakdown of all loaded modules and their size in
193 * kilobytes. Modules are ordered from largest to smallest.
196 // Map each module to a descriptor object.
197 var modules = $.map( inspect.getLoadedModules(), function ( module ) {
200 size: inspect.getModuleSize( module )
204 // Sort module descriptors by size, largest first.
205 sortByProperty( modules, 'size', true );
207 // Convert size to human-readable string.
208 $.each( modules, function ( i, module ) {
209 module.size = humanSize( module.size );
216 * For each module with styles, count the number of selectors, and
217 * count how many match against some element currently in the DOM.
222 $.each( inspect.getLoadedModules(), function ( index, name ) {
223 var css, stats, module = mw.loader.moduleRegistry[ name ];
226 css = module.style.css.join();
227 } catch ( e ) { return; } // skip
229 stats = inspect.auditSelectors( css );
232 allSelectors: stats.total,
233 matchedSelectors: stats.matched,
234 percentMatched: stats.total !== 0 ?
235 ( stats.matched / stats.total * 100 ).toFixed( 2 ) + '%' : null
238 sortByProperty( modules, 'allSelectors', true );
243 * Report stats on mw.loader.store: the number of localStorage
244 * cache hits and misses, the number of items purged from the
245 * cache, and the total size of the module blob in localStorage.
248 var raw, stats = { enabled: mw.loader.store.enabled };
249 if ( stats.enabled ) {
250 $.extend( stats, mw.loader.store.stats );
252 raw = localStorage.getItem( mw.loader.store.getStoreKey() );
253 stats.totalSize = humanSize( $.byteLength( raw ) );
261 * Perform a string search across the JavaScript and CSS source code
262 * of all loaded modules and return an array of the names of the
263 * modules that matched.
265 * @param {string|RegExp} pattern String or regexp to match.
266 * @return {Array} Array of the names of modules that matched.
268 grep: function ( pattern ) {
269 if ( typeof pattern.test !== 'function' ) {
270 pattern = new RegExp( mw.RegExp.escape( pattern ), 'g' );
273 return $.grep( inspect.getLoadedModules(), function ( moduleName ) {
274 var module = mw.loader.moduleRegistry[ moduleName ];
276 // Grep module's JavaScript
277 if ( $.isFunction( module.script ) && pattern.test( module.script.toString() ) ) {
283 $.isPlainObject( module.style ) && $.isArray( module.style.css )
284 && pattern.test( module.style.css.join( '' ) )
286 // Module's CSS source matches
295 if ( mw.config.get( 'debug' ) ) {
296 mw.log( 'mw.inspect: reports are not available in debug mode.' );
299 mw.inspect = inspect;
301 }( mediaWiki, jQuery ) );