2 * Tools for inspecting page composition and performance.
8 /* eslint-disable no-console */
10 ( function ( mw, $ ) {
13 hasOwn = Object.prototype.hasOwnProperty;
15 function sortByProperty( array, prop, descending ) {
16 var order = descending ? -1 : 1;
17 return array.sort( function ( a, b ) {
18 return a[ prop ] > b[ prop ] ? order : a[ prop ] < b[ prop ] ? -order : 0;
22 function humanSize( bytes ) {
24 units = [ '', ' KiB', ' MiB', ' GiB', ' TiB', ' PiB' ];
26 if ( !$.isNumeric( bytes ) || bytes === 0 ) { return bytes; }
28 for ( i = 0; bytes >= 1024; bytes /= 1024 ) { i++; }
29 // Maintain one decimal for kB and above, but don't
30 // add ".0" for bytes.
31 return bytes.toFixed( i > 0 ? 1 : 0 ) + units[ i ];
41 * Return a map of all dependency relationships between loaded modules.
43 * @return {Object} Maps module names to objects. Each sub-object has
44 * two properties, 'requires' and 'requiredBy'.
46 getDependencyGraph: function () {
47 var modules = inspect.getLoadedModules(),
50 $.each( modules, function ( moduleIndex, moduleName ) {
51 var dependencies = mw.loader.moduleRegistry[ moduleName ].dependencies || [];
53 if ( !hasOwn.call( graph, moduleName ) ) {
54 graph[ moduleName ] = { requiredBy: [] };
56 graph[ moduleName ].requires = dependencies;
58 $.each( dependencies, function ( depIndex, depName ) {
59 if ( !hasOwn.call( graph, depName ) ) {
60 graph[ depName ] = { requiredBy: [] };
62 graph[ depName ].requiredBy.push( moduleName );
69 * Calculate the byte size of a ResourceLoader module.
71 * @param {string} moduleName The name of the module
72 * @return {number|null} Module size in bytes or null
74 getModuleSize: function ( moduleName ) {
75 var module = mw.loader.moduleRegistry[ moduleName ],
78 if ( mw.loader.getState( moduleName ) !== 'ready' ) {
82 if ( !module.style && !module.script ) {
87 if ( module.style && $.isArray( module.style.css ) ) {
88 $.each( module.style.css, function ( i, stylesheet ) {
89 payload += $.byteLength( stylesheet );
94 if ( $.isFunction( module.script ) ) {
95 payload += $.byteLength( module.script.toString() );
102 * Given CSS source, count both the total number of selectors it
103 * contains and the number which match some element in the current
106 * @param {string} css CSS source
107 * @return {Object} Selector counts
108 * @return {number} return.selectors Total number of selectors
109 * @return {number} return.matched Number of matched selectors
111 auditSelectors: function ( css ) {
112 var selectors = { total: 0, matched: 0 },
113 style = document.createElement( 'style' );
115 style.textContent = css;
116 document.body.appendChild( style );
117 $.each( style.sheet.cssRules, function ( index, rule ) {
119 // document.querySelector() on prefixed pseudo-elements can throw exceptions
120 // in Firefox and Safari. Ignore these exceptions.
121 // https://bugs.webkit.org/show_bug.cgi?id=149160
122 // https://bugzilla.mozilla.org/show_bug.cgi?id=1204880
124 if ( document.querySelector( rule.selectorText ) !== null ) {
129 document.body.removeChild( style );
134 * Get a list of all loaded ResourceLoader modules.
136 * @return {Array} List of module names
138 getLoadedModules: function () {
139 return $.grep( mw.loader.getModuleNames(), function ( module ) {
140 return mw.loader.getState( module ) === 'ready';
145 * Print tabular data to the console, using console.table, console.log,
146 * or mw.log (in declining order of preference).
148 * @param {Array} data Tabular data represented as an array of objects
149 * with common properties.
151 dumpTable: function ( data ) {
153 // Bartosz made me put this here.
154 if ( window.opera ) { throw window.opera; }
155 // Use Function.prototype#call to force an exception on Firefox,
156 // which doesn't define console#table but doesn't complain if you
158 console.table.call( console, data );
162 console.log( JSON.stringify( data, null, 2 ) );
169 * Generate and print one more reports. When invoked with no arguments,
172 * @param {...string} [reports] Report names to run, or unset to print
173 * all available reports.
175 runReports: function () {
176 var reports = arguments.length > 0 ?
177 Array.prototype.slice.call( arguments ) :
178 $.map( inspect.reports, function ( v, k ) { return k; } );
180 $.each( reports, function ( index, name ) {
181 inspect.dumpTable( inspect.reports[ name ]() );
186 * @class mw.inspect.reports
191 * Generate a breakdown of all loaded modules and their size in
192 * kilobytes. Modules are ordered from largest to smallest.
194 * @return {Object[]} Size reports
197 // Map each module to a descriptor object.
198 var modules = $.map( inspect.getLoadedModules(), function ( module ) {
201 size: inspect.getModuleSize( module )
205 // Sort module descriptors by size, largest first.
206 sortByProperty( modules, 'size', true );
208 // Convert size to human-readable string.
209 $.each( modules, function ( i, module ) {
210 module.sizeInBytes = module.size;
211 module.size = humanSize( module.size );
218 * For each module with styles, count the number of selectors, and
219 * count how many match against some element currently in the DOM.
221 * @return {Object[]} CSS reports
226 $.each( inspect.getLoadedModules(), function ( index, name ) {
227 var css, stats, module = mw.loader.moduleRegistry[ name ];
230 css = module.style.css.join();
231 } catch ( e ) { return; } // skip
233 stats = inspect.auditSelectors( css );
236 allSelectors: stats.total,
237 matchedSelectors: stats.matched,
238 percentMatched: stats.total !== 0 ?
239 ( stats.matched / stats.total * 100 ).toFixed( 2 ) + '%' : null
242 sortByProperty( modules, 'allSelectors', true );
247 * Report stats on mw.loader.store: the number of localStorage
248 * cache hits and misses, the number of items purged from the
249 * cache, and the total size of the module blob in localStorage.
251 * @return {Object[]} Store stats
254 var raw, stats = { enabled: mw.loader.store.enabled };
255 if ( stats.enabled ) {
256 $.extend( stats, mw.loader.store.stats );
258 raw = localStorage.getItem( mw.loader.store.getStoreKey() );
259 stats.totalSizeInBytes = $.byteLength( raw );
260 stats.totalSize = humanSize( $.byteLength( raw ) );
268 * Perform a string search across the JavaScript and CSS source code
269 * of all loaded modules and return an array of the names of the
270 * modules that matched.
272 * @param {string|RegExp} pattern String or regexp to match.
273 * @return {Array} Array of the names of modules that matched.
275 grep: function ( pattern ) {
276 if ( typeof pattern.test !== 'function' ) {
277 pattern = new RegExp( mw.RegExp.escape( pattern ), 'g' );
280 return $.grep( inspect.getLoadedModules(), function ( moduleName ) {
281 var module = mw.loader.moduleRegistry[ moduleName ];
283 // Grep module's JavaScript
284 if ( $.isFunction( module.script ) && pattern.test( module.script.toString() ) ) {
290 $.isPlainObject( module.style ) && $.isArray( module.style.css ) &&
291 pattern.test( module.style.css.join( '' ) )
293 // Module's CSS source matches
302 if ( mw.config.get( 'debug' ) ) {
303 mw.log( 'mw.inspect: reports are not available in debug mode.' );
306 mw.inspect = inspect;
308 }( mediaWiki, jQuery ) );