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 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 if ( document
.querySelector( rule
.selectorText
) !== null ) {
124 document
.body
.removeChild( style
);
129 * Get a list of all loaded ResourceLoader modules.
131 * @return {Array} List of module names
133 getLoadedModules: function () {
134 return $.grep( mw
.loader
.getModuleNames(), function ( module
) {
135 return mw
.loader
.getState( module
) === 'ready';
140 * Print tabular data to the console, using console.table, console.log,
141 * or mw.log (in declining order of preference).
143 * @param {Array} data Tabular data represented as an array of objects
144 * with common properties.
146 dumpTable: function ( data
) {
148 // Bartosz made me put this here.
149 if ( window
.opera
) { throw window
.opera
; }
150 // Use Function.prototype#call to force an exception on Firefox,
151 // which doesn't define console#table but doesn't complain if you
153 console
.table
.call( console
, data
);
157 console
.log( JSON
.stringify( data
, null, 2 ) );
164 * Generate and print one more reports. When invoked with no arguments,
167 * @param {string...} [reports] Report names to run, or unset to print
168 * all available reports.
170 runReports: function () {
171 var reports
= arguments
.length
> 0 ?
172 Array
.prototype.slice
.call( arguments
) :
173 $.map( inspect
.reports
, function ( v
, k
) { return k
; } );
175 $.each( reports
, function ( index
, name
) {
176 inspect
.dumpTable( inspect
.reports
[name
]() );
181 * @class mw.inspect.reports
186 * Generate a breakdown of all loaded modules and their size in
187 * kilobytes. Modules are ordered from largest to smallest.
190 // Map each module to a descriptor object.
191 var modules
= $.map( inspect
.getLoadedModules(), function ( module
) {
194 size
: inspect
.getModuleSize( module
)
198 // Sort module descriptors by size, largest first.
199 sortByProperty( modules
, 'size', true );
201 // Convert size to human-readable string.
202 $.each( modules
, function ( i
, module
) {
203 module
.size
= humanSize( module
.size
);
210 * For each module with styles, count the number of selectors, and
211 * count how many match against some element currently in the DOM.
216 $.each( inspect
.getLoadedModules(), function ( index
, name
) {
217 var css
, stats
, module
= mw
.loader
.moduleRegistry
[name
];
220 css
= module
.style
.css
.join();
221 } catch ( e
) { return; } // skip
223 stats
= inspect
.auditSelectors( css
);
226 allSelectors
: stats
.total
,
227 matchedSelectors
: stats
.matched
,
228 percentMatched
: stats
.total
!== 0 ?
229 ( stats
.matched
/ stats
.total
* 100 ).toFixed( 2 ) + '%' : null
232 sortByProperty( modules
, 'allSelectors', true );
237 * Report stats on mw.loader.store: the number of localStorage
238 * cache hits and misses, the number of items purged from the
239 * cache, and the total size of the module blob in localStorage.
242 var raw
, stats
= { enabled
: mw
.loader
.store
.enabled
};
243 if ( stats
.enabled
) {
244 $.extend( stats
, mw
.loader
.store
.stats
);
246 raw
= localStorage
.getItem( mw
.loader
.store
.getStoreKey() );
247 stats
.totalSize
= humanSize( $.byteLength( raw
) );
255 * Perform a string search across the JavaScript and CSS source code
256 * of all loaded modules and return an array of the names of the
257 * modules that matched.
259 * @param {string|RegExp} pattern String or regexp to match.
260 * @return {Array} Array of the names of modules that matched.
262 grep: function ( pattern
) {
263 if ( typeof pattern
.test
!== 'function' ) {
264 // Based on Y.Escape.regex from YUI v3.15.0
265 pattern
= new RegExp( pattern
.replace( /[\-$\^*()+\[\]{}|\\,.?\s]/g, '\\$&' ), 'g' );
268 return $.grep( inspect
.getLoadedModules(), function ( moduleName
) {
269 var module
= mw
.loader
.moduleRegistry
[moduleName
];
271 // Grep module's JavaScript
272 if ( $.isFunction( module
.script
) && pattern
.test( module
.script
.toString() ) ) {
278 $.isPlainObject( module
.style
) && $.isArray( module
.style
.css
)
279 && pattern
.test( module
.style
.css
.join( '' ) )
281 // Module's CSS source matches
290 if ( mw
.config
.get( 'debug' ) ) {
291 mw
.log( 'mw.inspect: reports are not available in debug mode.' );
294 mw
.inspect
= inspect
;
296 }( mediaWiki
, jQuery
) );