2 * The mediawiki.inspect module.
8 /* eslint-disable no-console */
12 // mw.inspect is a singleton class with static methods
13 // that itself can also be invoked as a function (mediawiki.base/mw#inspect).
14 // In JavaScript, that is implemented by starting with a function,
15 // and subsequently setting additional properties on the function object.
18 * Tools for inspecting page composition and performance.
24 var inspect
= mw
.inspect
,
25 byteLength
= require( 'mediawiki.String' ).byteLength
,
26 hasOwn
= Object
.prototype.hasOwnProperty
;
28 function sortByProperty( array
, prop
, descending
) {
29 var order
= descending
? -1 : 1;
30 return array
.sort( function ( a
, b
) {
31 if ( a
[ prop
] === undefined || b
[ prop
] === undefined ) {
32 // Sort undefined to the end, regardless of direction
33 return a
[ prop
] !== undefined ? -1 : b
[ prop
] !== undefined ? 1 : 0;
35 return a
[ prop
] > b
[ prop
] ? order
: a
[ prop
] < b
[ prop
] ? -order
: 0;
39 function humanSize( bytes
) {
41 units
= [ '', ' KiB', ' MiB', ' GiB', ' TiB', ' PiB' ];
43 if ( !$.isNumeric( bytes
) || bytes
=== 0 ) {
47 for ( i
= 0; bytes
>= 1024; bytes
/= 1024 ) {
50 // Maintain one decimal for kB and above, but don't
51 // add ".0" for bytes.
52 return bytes
.toFixed( i
> 0 ? 1 : 0 ) + units
[ i
];
56 * Return a map of all dependency relationships between loaded modules.
58 * @return {Object} Maps module names to objects. Each sub-object has
59 * two properties, 'requires' and 'requiredBy'.
61 inspect
.getDependencyGraph = function () {
62 var modules
= inspect
.getLoadedModules(),
65 modules
.forEach( function ( moduleName
) {
66 var dependencies
= mw
.loader
.moduleRegistry
[ moduleName
].dependencies
|| [];
68 if ( !hasOwn
.call( graph
, moduleName
) ) {
69 graph
[ moduleName
] = { requiredBy
: [] };
71 graph
[ moduleName
].requires
= dependencies
;
73 dependencies
.forEach( function ( depName
) {
74 if ( !hasOwn
.call( graph
, depName
) ) {
75 graph
[ depName
] = { requiredBy
: [] };
77 graph
[ depName
].requiredBy
.push( moduleName
);
84 * Calculate the byte size of a ResourceLoader module.
86 * @param {string} moduleName The name of the module
87 * @return {number|null} Module size in bytes or null
89 inspect
.getModuleSize = function ( moduleName
) {
90 var module
= mw
.loader
.moduleRegistry
[ moduleName
],
93 if ( module
.state
!== 'ready' ) {
97 if ( !module
.style
&& !module
.script
) {
101 function getFunctionBody( func
) {
102 return String( func
)
103 // To ensure a deterministic result, replace the start of the function
104 // declaration with a fixed string. For example, in Chrome 55, it seems
105 // V8 seemingly-at-random decides to sometimes put a line break between
106 // the opening brace and first statement of the function body. T159751.
107 .replace( /^\s*function\s*\([^)]*\)\s*{\s*/, 'function(){' )
108 .replace( /\s*}\s*$/, '}' );
111 // Based on the load.php response for this module.
112 // For example: `mw.loader.implement("example", function(){}, {"css":[".x{color:red}"]});`
113 // @see mw.loader.store.set().
121 // Trim trailing null or empty object, as load.php would have done.
122 // @see ResourceLoader::makeLoaderImplementScript and ResourceLoader::trimArray.
125 if ( args
[ i
] === null || ( $.isPlainObject( args
[ i
] ) && $.isEmptyObject( args
[ i
] ) ) ) {
133 for ( i
= 0; i
< args
.length
; i
++ ) {
134 if ( typeof args
[ i
] === 'function' ) {
135 size
+= byteLength( getFunctionBody( args
[ i
] ) );
137 size
+= byteLength( JSON
.stringify( args
[ i
] ) );
145 * Given CSS source, count both the total number of selectors it
146 * contains and the number which match some element in the current
149 * @param {string} css CSS source
150 * @return {Object} Selector counts
151 * @return {number} return.selectors Total number of selectors
152 * @return {number} return.matched Number of matched selectors
154 inspect
.auditSelectors = function ( css
) {
155 var selectors
= { total
: 0, matched
: 0 },
156 style
= document
.createElement( 'style' );
158 style
.textContent
= css
;
159 document
.body
.appendChild( style
);
160 // eslint-disable-next-line jquery/no-each-util
161 $.each( style
.sheet
.cssRules
, function ( index
, rule
) {
163 // document.querySelector() on prefixed pseudo-elements can throw exceptions
164 // in Firefox and Safari. Ignore these exceptions.
165 // https://bugs.webkit.org/show_bug.cgi?id=149160
166 // https://bugzilla.mozilla.org/show_bug.cgi?id=1204880
168 if ( document
.querySelector( rule
.selectorText
) !== null ) {
173 document
.body
.removeChild( style
);
178 * Get a list of all loaded ResourceLoader modules.
180 * @return {Array} List of module names
182 inspect
.getLoadedModules = function () {
183 return mw
.loader
.getModuleNames().filter( function ( module
) {
184 return mw
.loader
.getState( module
) === 'ready';
189 * Print tabular data to the console, using console.table, console.log,
190 * or mw.log (in declining order of preference).
192 * @param {Array} data Tabular data represented as an array of objects
193 * with common properties.
195 inspect
.dumpTable = function ( data
) {
197 // Use Function.prototype#call to force an exception on Firefox,
198 // which doesn't define console#table but doesn't complain if you
200 // eslint-disable-next-line no-useless-call
201 console
.table
.call( console
, data
);
205 console
.log( JSON
.stringify( data
, null, 2 ) );
210 * Generate and print reports.
212 * When invoked without arguments, prints all available reports.
214 * @param {...string} [reports] One or more of "size", "css", "store", or "time".
216 inspect
.runReports = function () {
217 var reports
= arguments
.length
> 0 ?
218 Array
.prototype.slice
.call( arguments
) :
219 Object
.keys( inspect
.reports
);
221 reports
.forEach( function ( name
) {
222 if ( console
.group
) {
223 console
.group( 'mw.inspect ' + name
+ ' report' );
225 console
.log( 'mw.inspect ' + name
+ ' report' );
227 inspect
.dumpTable( inspect
.reports
[ name
]() );
228 if ( console
.group
) {
229 console
.groupEnd( 'mw.inspect ' + name
+ ' report' );
235 * Perform a string search across the JavaScript and CSS source code
236 * of all loaded modules and return an array of the names of the
237 * modules that matched.
239 * @param {string|RegExp} pattern String or regexp to match.
240 * @return {Array} Array of the names of modules that matched.
242 inspect
.grep = function ( pattern
) {
243 if ( typeof pattern
.test
!== 'function' ) {
244 pattern
= new RegExp( mw
.RegExp
.escape( pattern
), 'g' );
247 return inspect
.getLoadedModules().filter( function ( moduleName
) {
248 var module
= mw
.loader
.moduleRegistry
[ moduleName
];
250 // Grep module's JavaScript
251 if ( typeof module
.script
=== 'function' && pattern
.test( module
.script
.toString() ) ) {
257 $.isPlainObject( module
.style
) && Array
.isArray( module
.style
.css
) &&
258 pattern
.test( module
.style
.css
.join( '' ) )
260 // Module's CSS source matches
270 * @class mw.inspect.reports
275 * Generate a breakdown of all loaded modules and their size in
276 * kilobytes. Modules are ordered from largest to smallest.
278 * @return {Object[]} Size reports
281 // Map each module to a descriptor object.
282 var modules
= inspect
.getLoadedModules().map( function ( module
) {
285 size
: inspect
.getModuleSize( module
)
289 // Sort module descriptors by size, largest first.
290 sortByProperty( modules
, 'size', true );
292 // Convert size to human-readable string.
293 modules
.forEach( function ( module
) {
294 module
.sizeInBytes
= module
.size
;
295 module
.size
= humanSize( module
.size
);
302 * For each module with styles, count the number of selectors, and
303 * count how many match against some element currently in the DOM.
305 * @return {Object[]} CSS reports
310 inspect
.getLoadedModules().forEach( function ( name
) {
311 var css
, stats
, module
= mw
.loader
.moduleRegistry
[ name
];
314 css
= module
.style
.css
.join();
315 } catch ( e
) { return; } // skip
317 stats
= inspect
.auditSelectors( css
);
320 allSelectors
: stats
.total
,
321 matchedSelectors
: stats
.matched
,
322 percentMatched
: stats
.total
!== 0 ?
323 ( stats
.matched
/ stats
.total
* 100 ).toFixed( 2 ) + '%' : null
326 sortByProperty( modules
, 'allSelectors', true );
331 * Report stats on mw.loader.store: the number of localStorage
332 * cache hits and misses, the number of items purged from the
333 * cache, and the total size of the module blob in localStorage.
335 * @return {Object[]} Store stats
338 var raw
, stats
= { enabled
: mw
.loader
.store
.enabled
};
339 if ( stats
.enabled
) {
340 $.extend( stats
, mw
.loader
.store
.stats
);
342 raw
= localStorage
.getItem( mw
.loader
.store
.getStoreKey() );
343 stats
.totalSizeInBytes
= byteLength( raw
);
344 stats
.totalSize
= humanSize( byteLength( raw
) );
351 * Generate a breakdown of all loaded modules and their time
352 * spent during initialisation (measured in milliseconds).
354 * This timing data is collected by mw.loader.profiler.
356 * @return {Object[]} Table rows
361 if ( !mw
.loader
.profiler
) {
362 mw
.log
.warn( 'mw.inspect: The time report requires $wgResourceLoaderEnableJSProfiler.' );
366 modules
= inspect
.getLoadedModules()
367 .map( function ( moduleName
) {
368 return mw
.loader
.profiler
.getProfile( moduleName
);
370 .filter( function ( perf
) {
371 // Exclude modules that reached "ready" state without involvement from mw.loader.
372 // This is primarily styles-only as loaded via <link rel="stylesheet">.
373 return perf
!== null;
376 // Sort by total time spent, highest first.
377 sortByProperty( modules
, 'total', true );
379 // Add human-readable strings
380 modules
.forEach( function ( module
) {
381 module
.totalInMs
= module
.total
;
382 module
.total
= module
.totalInMs
.toLocaleString() + ' ms';
389 if ( mw
.config
.get( 'debug' ) ) {
390 mw
.log( 'mw.inspect: reports are not available in debug mode.' );