6c4b80d2ae51ce82f4388e40640918bfe38f3732
2 * The mediawiki.inspect module.
8 /* eslint-disable no-console */
10 ( function ( mw
, $ ) {
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 return a
[ prop
] > b
[ prop
] ? order
: a
[ prop
] < b
[ prop
] ? -order
: 0;
35 function humanSize( bytes
) {
37 units
= [ '', ' KiB', ' MiB', ' GiB', ' TiB', ' PiB' ];
39 if ( !$.isNumeric( bytes
) || bytes
=== 0 ) { return bytes
; }
41 for ( i
= 0; bytes
>= 1024; bytes
/= 1024 ) { i
++; }
42 // Maintain one decimal for kB and above, but don't
43 // add ".0" for bytes.
44 return bytes
.toFixed( i
> 0 ? 1 : 0 ) + units
[ i
];
48 * Return a map of all dependency relationships between loaded modules.
50 * @return {Object} Maps module names to objects. Each sub-object has
51 * two properties, 'requires' and 'requiredBy'.
53 inspect
.getDependencyGraph = function () {
54 var modules
= inspect
.getLoadedModules(),
57 modules
.forEach( function ( moduleName
) {
58 var dependencies
= mw
.loader
.moduleRegistry
[ moduleName
].dependencies
|| [];
60 if ( !hasOwn
.call( graph
, moduleName
) ) {
61 graph
[ moduleName
] = { requiredBy
: [] };
63 graph
[ moduleName
].requires
= dependencies
;
65 dependencies
.forEach( function ( depName
) {
66 if ( !hasOwn
.call( graph
, depName
) ) {
67 graph
[ depName
] = { requiredBy
: [] };
69 graph
[ depName
].requiredBy
.push( moduleName
);
76 * Calculate the byte size of a ResourceLoader module.
78 * @param {string} moduleName The name of the module
79 * @return {number|null} Module size in bytes or null
81 inspect
.getModuleSize = function ( moduleName
) {
82 var module
= mw
.loader
.moduleRegistry
[ moduleName
],
85 if ( module
.state
!== 'ready' ) {
89 if ( !module
.style
&& !module
.script
) {
93 function getFunctionBody( func
) {
95 // To ensure a deterministic result, replace the start of the function
96 // declaration with a fixed string. For example, in Chrome 55, it seems
97 // V8 seemingly-at-random decides to sometimes put a line break between
98 // the opening brace and first statement of the function body. T159751.
99 .replace( /^\s*function\s*\([^)]*\)\s*{\s*/, 'function(){' )
100 .replace( /\s*}\s*$/, '}' );
103 // Based on the load.php response for this module.
104 // For example: `mw.loader.implement("example", function(){}, {"css":[".x{color:red}"]});`
105 // @see mw.loader.store.set().
113 // Trim trailing null or empty object, as load.php would have done.
114 // @see ResourceLoader::makeLoaderImplementScript and ResourceLoader::trimArray.
117 if ( args
[ i
] === null || ( $.isPlainObject( args
[ i
] ) && $.isEmptyObject( args
[ i
] ) ) ) {
125 for ( i
= 0; i
< args
.length
; i
++ ) {
126 if ( typeof args
[ i
] === 'function' ) {
127 size
+= byteLength( getFunctionBody( args
[ i
] ) );
129 size
+= byteLength( JSON
.stringify( args
[ i
] ) );
137 * Given CSS source, count both the total number of selectors it
138 * contains and the number which match some element in the current
141 * @param {string} css CSS source
142 * @return {Object} Selector counts
143 * @return {number} return.selectors Total number of selectors
144 * @return {number} return.matched Number of matched selectors
146 inspect
.auditSelectors = function ( css
) {
147 var selectors
= { total
: 0, matched
: 0 },
148 style
= document
.createElement( 'style' );
150 style
.textContent
= css
;
151 document
.body
.appendChild( style
);
152 $.each( style
.sheet
.cssRules
, function ( index
, rule
) {
154 // document.querySelector() on prefixed pseudo-elements can throw exceptions
155 // in Firefox and Safari. Ignore these exceptions.
156 // https://bugs.webkit.org/show_bug.cgi?id=149160
157 // https://bugzilla.mozilla.org/show_bug.cgi?id=1204880
159 if ( document
.querySelector( rule
.selectorText
) !== null ) {
164 document
.body
.removeChild( style
);
169 * Get a list of all loaded ResourceLoader modules.
171 * @return {Array} List of module names
173 inspect
.getLoadedModules = function () {
174 return mw
.loader
.getModuleNames().filter( function ( module
) {
175 return mw
.loader
.getState( module
) === 'ready';
180 * Print tabular data to the console, using console.table, console.log,
181 * or mw.log (in declining order of preference).
183 * @param {Array} data Tabular data represented as an array of objects
184 * with common properties.
186 inspect
.dumpTable = function ( data
) {
188 // Use Function.prototype#call to force an exception on Firefox,
189 // which doesn't define console#table but doesn't complain if you
191 // eslint-disable-next-line no-useless-call
192 console
.table
.call( console
, data
);
196 console
.log( JSON
.stringify( data
, null, 2 ) );
201 * Generate and print reports.
203 * When invoked without arguments, prints all available reports.
205 * @param {...string} [reports] One or more of "size", "css", or "store".
207 inspect
.runReports = function () {
208 var reports
= arguments
.length
> 0 ?
209 Array
.prototype.slice
.call( arguments
) :
210 Object
.keys( inspect
.reports
);
212 reports
.forEach( function ( name
) {
213 if ( console
.group
) {
214 console
.group( 'mw.inspect ' + name
+ ' report' );
216 console
.log( 'mw.inspect ' + name
+ ' report' );
218 inspect
.dumpTable( inspect
.reports
[ name
]() );
219 if ( console
.group
) {
220 console
.groupEnd( 'mw.inspect ' + name
+ ' report' );
226 * Perform a string search across the JavaScript and CSS source code
227 * of all loaded modules and return an array of the names of the
228 * modules that matched.
230 * @param {string|RegExp} pattern String or regexp to match.
231 * @return {Array} Array of the names of modules that matched.
233 inspect
.grep = function ( pattern
) {
234 if ( typeof pattern
.test
!== 'function' ) {
235 pattern
= new RegExp( mw
.RegExp
.escape( pattern
), 'g' );
238 return inspect
.getLoadedModules().filter( function ( moduleName
) {
239 var module
= mw
.loader
.moduleRegistry
[ moduleName
];
241 // Grep module's JavaScript
242 if ( typeof module
.script
=== 'function' && pattern
.test( module
.script
.toString() ) ) {
248 $.isPlainObject( module
.style
) && Array
.isArray( module
.style
.css
) &&
249 pattern
.test( module
.style
.css
.join( '' ) )
251 // Module's CSS source matches
260 * @class mw.inspect.reports
265 * Generate a breakdown of all loaded modules and their size in
266 * kilobytes. Modules are ordered from largest to smallest.
268 * @return {Object[]} Size reports
271 // Map each module to a descriptor object.
272 var modules
= inspect
.getLoadedModules().map( function ( module
) {
275 size
: inspect
.getModuleSize( module
)
279 // Sort module descriptors by size, largest first.
280 sortByProperty( modules
, 'size', true );
282 // Convert size to human-readable string.
283 modules
.forEach( function ( module
) {
284 module
.sizeInBytes
= module
.size
;
285 module
.size
= humanSize( module
.size
);
292 * For each module with styles, count the number of selectors, and
293 * count how many match against some element currently in the DOM.
295 * @return {Object[]} CSS reports
300 inspect
.getLoadedModules().forEach( function ( name
) {
301 var css
, stats
, module
= mw
.loader
.moduleRegistry
[ name
];
304 css
= module
.style
.css
.join();
305 } catch ( e
) { return; } // skip
307 stats
= inspect
.auditSelectors( css
);
310 allSelectors
: stats
.total
,
311 matchedSelectors
: stats
.matched
,
312 percentMatched
: stats
.total
!== 0 ?
313 ( stats
.matched
/ stats
.total
* 100 ).toFixed( 2 ) + '%' : null
316 sortByProperty( modules
, 'allSelectors', true );
321 * Report stats on mw.loader.store: the number of localStorage
322 * cache hits and misses, the number of items purged from the
323 * cache, and the total size of the module blob in localStorage.
325 * @return {Object[]} Store stats
328 var raw
, stats
= { enabled
: mw
.loader
.store
.enabled
};
329 if ( stats
.enabled
) {
330 $.extend( stats
, mw
.loader
.store
.stats
);
332 raw
= localStorage
.getItem( mw
.loader
.store
.getStoreKey() );
333 stats
.totalSizeInBytes
= byteLength( raw
);
334 stats
.totalSize
= humanSize( byteLength( raw
) );
341 if ( mw
.config
.get( 'debug' ) ) {
342 mw
.log( 'mw.inspect: reports are not available in debug mode.' );
345 }( mediaWiki
, jQuery
) );