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() );
98 // Tally templates and messages. Calculate their JSON size so that keys
99 // are included in the module size - in the case of messages, keys can be
100 // longer than values - and so that empty objects are also included.
101 $.each( [ module
.templates
, module
.messages
], function ( i
, object
) {
103 payload
+= $.byteLength( JSON
.stringify( object
) );
111 * Given CSS source, count both the total number of selectors it
112 * contains and the number which match some element in the current
115 * @param {string} css CSS source
116 * @return {Object} Selector counts
117 * @return {number} return.selectors Total number of selectors
118 * @return {number} return.matched Number of matched selectors
120 auditSelectors: function ( css
) {
121 var selectors
= { total
: 0, matched
: 0 },
122 style
= document
.createElement( 'style' );
124 style
.textContent
= css
;
125 document
.body
.appendChild( style
);
126 $.each( style
.sheet
.cssRules
, function ( index
, rule
) {
128 // document.querySelector() on prefixed pseudo-elements can throw exceptions
129 // in Firefox and Safari. Ignore these exceptions.
130 // https://bugs.webkit.org/show_bug.cgi?id=149160
131 // https://bugzilla.mozilla.org/show_bug.cgi?id=1204880
133 if ( document
.querySelector( rule
.selectorText
) !== null ) {
138 document
.body
.removeChild( style
);
143 * Get a list of all loaded ResourceLoader modules.
145 * @return {Array} List of module names
147 getLoadedModules: function () {
148 return $.grep( mw
.loader
.getModuleNames(), function ( module
) {
149 return mw
.loader
.getState( module
) === 'ready';
154 * Print tabular data to the console, using console.table, console.log,
155 * or mw.log (in declining order of preference).
157 * @param {Array} data Tabular data represented as an array of objects
158 * with common properties.
160 dumpTable: function ( data
) {
162 // Bartosz made me put this here.
163 if ( window
.opera
) { throw window
.opera
; }
164 // Use Function.prototype#call to force an exception on Firefox,
165 // which doesn't define console#table but doesn't complain if you
167 console
.table
.call( console
, data
);
171 console
.log( JSON
.stringify( data
, null, 2 ) );
178 * Generate and print one more reports. When invoked with no arguments,
181 * @param {...string} [reports] Report names to run, or unset to print
182 * all available reports.
184 runReports: function () {
185 var reports
= arguments
.length
> 0 ?
186 Array
.prototype.slice
.call( arguments
) :
187 $.map( inspect
.reports
, function ( v
, k
) { return k
; } );
189 $.each( reports
, function ( index
, name
) {
190 inspect
.dumpTable( inspect
.reports
[ name
]() );
195 * @class mw.inspect.reports
200 * Generate a breakdown of all loaded modules and their size in
201 * kilobytes. Modules are ordered from largest to smallest.
203 * @return {Object[]} Size reports
206 // Map each module to a descriptor object.
207 var modules
= $.map( inspect
.getLoadedModules(), function ( module
) {
210 size
: inspect
.getModuleSize( module
)
214 // Sort module descriptors by size, largest first.
215 sortByProperty( modules
, 'size', true );
217 // Convert size to human-readable string.
218 $.each( modules
, function ( i
, module
) {
219 module
.sizeInBytes
= module
.size
;
220 module
.size
= humanSize( module
.size
);
227 * For each module with styles, count the number of selectors, and
228 * count how many match against some element currently in the DOM.
230 * @return {Object[]} CSS reports
235 $.each( inspect
.getLoadedModules(), function ( index
, name
) {
236 var css
, stats
, module
= mw
.loader
.moduleRegistry
[ name
];
239 css
= module
.style
.css
.join();
240 } catch ( e
) { return; } // skip
242 stats
= inspect
.auditSelectors( css
);
245 allSelectors
: stats
.total
,
246 matchedSelectors
: stats
.matched
,
247 percentMatched
: stats
.total
!== 0 ?
248 ( stats
.matched
/ stats
.total
* 100 ).toFixed( 2 ) + '%' : null
251 sortByProperty( modules
, 'allSelectors', true );
256 * Report stats on mw.loader.store: the number of localStorage
257 * cache hits and misses, the number of items purged from the
258 * cache, and the total size of the module blob in localStorage.
260 * @return {Object[]} Store stats
263 var raw
, stats
= { enabled
: mw
.loader
.store
.enabled
};
264 if ( stats
.enabled
) {
265 $.extend( stats
, mw
.loader
.store
.stats
);
267 raw
= localStorage
.getItem( mw
.loader
.store
.getStoreKey() );
268 stats
.totalSizeInBytes
= $.byteLength( raw
);
269 stats
.totalSize
= humanSize( $.byteLength( raw
) );
277 * Perform a string search across the JavaScript and CSS source code
278 * of all loaded modules and return an array of the names of the
279 * modules that matched.
281 * @param {string|RegExp} pattern String or regexp to match.
282 * @return {Array} Array of the names of modules that matched.
284 grep: function ( pattern
) {
285 if ( typeof pattern
.test
!== 'function' ) {
286 pattern
= new RegExp( mw
.RegExp
.escape( pattern
), 'g' );
289 return $.grep( inspect
.getLoadedModules(), function ( moduleName
) {
290 var module
= mw
.loader
.moduleRegistry
[ moduleName
];
292 // Grep module's JavaScript
293 if ( $.isFunction( module
.script
) && pattern
.test( module
.script
.toString() ) ) {
299 $.isPlainObject( module
.style
) && $.isArray( module
.style
.css
) &&
300 pattern
.test( module
.style
.css
.join( '' ) )
302 // Module's CSS source matches
311 if ( mw
.config
.get( 'debug' ) ) {
312 mw
.log( 'mw.inspect: reports are not available in debug mode.' );
315 mw
.inspect
= inspect
;
317 }( mediaWiki
, jQuery
) );