mediawiki.inspect: Simplify getModuleSize() by using module descriptor
[lhc/web/wiklou.git] / resources / src / mediawiki / mediawiki.inspect.js
1 /*!
2 * Tools for inspecting page composition and performance.
3 *
4 * @author Ori Livneh
5 * @since 1.22
6 */
7
8 /* eslint-disable no-console */
9
10 ( function ( mw, $ ) {
11
12 var inspect,
13 hasOwn = Object.prototype.hasOwnProperty;
14
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;
19 } );
20 }
21
22 function humanSize( bytes ) {
23 var i,
24 units = [ '', ' KiB', ' MiB', ' GiB', ' TiB', ' PiB' ];
25
26 if ( !$.isNumeric( bytes ) || bytes === 0 ) { return bytes; }
27
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 ];
32 }
33
34 /**
35 * @class mw.inspect
36 * @singleton
37 */
38 inspect = {
39
40 /**
41 * Return a map of all dependency relationships between loaded modules.
42 *
43 * @return {Object} Maps module names to objects. Each sub-object has
44 * two properties, 'requires' and 'requiredBy'.
45 */
46 getDependencyGraph: function () {
47 var modules = inspect.getLoadedModules(),
48 graph = {};
49
50 $.each( modules, function ( moduleIndex, moduleName ) {
51 var dependencies = mw.loader.moduleRegistry[ moduleName ].dependencies || [];
52
53 if ( !hasOwn.call( graph, moduleName ) ) {
54 graph[ moduleName ] = { requiredBy: [] };
55 }
56 graph[ moduleName ].requires = dependencies;
57
58 $.each( dependencies, function ( depIndex, depName ) {
59 if ( !hasOwn.call( graph, depName ) ) {
60 graph[ depName ] = { requiredBy: [] };
61 }
62 graph[ depName ].requiredBy.push( moduleName );
63 } );
64 } );
65 return graph;
66 },
67
68 /**
69 * Calculate the byte size of a ResourceLoader module.
70 *
71 * @param {string} moduleName The name of the module
72 * @return {number|null} Module size in bytes or null
73 */
74 getModuleSize: function ( moduleName ) {
75 var module = mw.loader.moduleRegistry[ moduleName ],
76 args, i;
77
78 if ( mw.loader.getState( moduleName ) !== 'ready' ) {
79 return null;
80 }
81
82 if ( !module.style && !module.script ) {
83 return 0;
84 }
85
86 // Reverse-engineer the load.php response for this module.
87 // For example: `mw.loader.implement("example", function(){}, );`
88 // @see mw.loader.store.set().
89 args = [
90 JSON.stringify( moduleName ),
91 // function, array of urls, or eval string
92 typeof module.script === 'function' ?
93 String( module.script ) :
94 JSON.stringify( module.script ),
95 JSON.stringify( module.style ),
96 JSON.stringify( module.messages ),
97 JSON.stringify( module.templates )
98 ];
99 // Trim trailing null or empty object, as load.php would have done.
100 // @see ResourceLoader::makeLoaderImplementScript and ResourceLoader::trimArray.
101 i = args.length;
102 while ( i-- ) {
103 if ( args[ i ] === '{}' || args[ i ] === 'null' ) {
104 args.splice( i, 1 );
105 } else {
106 break;
107 }
108 }
109
110 return $.byteLength( args.join( ',' ) );
111 },
112
113 /**
114 * Given CSS source, count both the total number of selectors it
115 * contains and the number which match some element in the current
116 * document.
117 *
118 * @param {string} css CSS source
119 * @return {Object} Selector counts
120 * @return {number} return.selectors Total number of selectors
121 * @return {number} return.matched Number of matched selectors
122 */
123 auditSelectors: function ( css ) {
124 var selectors = { total: 0, matched: 0 },
125 style = document.createElement( 'style' );
126
127 style.textContent = css;
128 document.body.appendChild( style );
129 $.each( style.sheet.cssRules, function ( index, rule ) {
130 selectors.total++;
131 // document.querySelector() on prefixed pseudo-elements can throw exceptions
132 // in Firefox and Safari. Ignore these exceptions.
133 // https://bugs.webkit.org/show_bug.cgi?id=149160
134 // https://bugzilla.mozilla.org/show_bug.cgi?id=1204880
135 try {
136 if ( document.querySelector( rule.selectorText ) !== null ) {
137 selectors.matched++;
138 }
139 } catch ( e ) {}
140 } );
141 document.body.removeChild( style );
142 return selectors;
143 },
144
145 /**
146 * Get a list of all loaded ResourceLoader modules.
147 *
148 * @return {Array} List of module names
149 */
150 getLoadedModules: function () {
151 return $.grep( mw.loader.getModuleNames(), function ( module ) {
152 return mw.loader.getState( module ) === 'ready';
153 } );
154 },
155
156 /**
157 * Print tabular data to the console, using console.table, console.log,
158 * or mw.log (in declining order of preference).
159 *
160 * @param {Array} data Tabular data represented as an array of objects
161 * with common properties.
162 */
163 dumpTable: function ( data ) {
164 try {
165 // Bartosz made me put this here.
166 if ( window.opera ) { throw window.opera; }
167 // Use Function.prototype#call to force an exception on Firefox,
168 // which doesn't define console#table but doesn't complain if you
169 // try to invoke it.
170 console.table.call( console, data );
171 return;
172 } catch ( e ) {}
173 try {
174 console.log( JSON.stringify( data, null, 2 ) );
175 return;
176 } catch ( e ) {}
177 mw.log( data );
178 },
179
180 /**
181 * Generate and print one more reports. When invoked with no arguments,
182 * print all reports.
183 *
184 * @param {...string} [reports] Report names to run, or unset to print
185 * all available reports.
186 */
187 runReports: function () {
188 var reports = arguments.length > 0 ?
189 Array.prototype.slice.call( arguments ) :
190 $.map( inspect.reports, function ( v, k ) { return k; } );
191
192 $.each( reports, function ( index, name ) {
193 inspect.dumpTable( inspect.reports[ name ]() );
194 } );
195 },
196
197 /**
198 * @class mw.inspect.reports
199 * @singleton
200 */
201 reports: {
202 /**
203 * Generate a breakdown of all loaded modules and their size in
204 * kilobytes. Modules are ordered from largest to smallest.
205 *
206 * @return {Object[]} Size reports
207 */
208 size: function () {
209 // Map each module to a descriptor object.
210 var modules = $.map( inspect.getLoadedModules(), function ( module ) {
211 return {
212 name: module,
213 size: inspect.getModuleSize( module )
214 };
215 } );
216
217 // Sort module descriptors by size, largest first.
218 sortByProperty( modules, 'size', true );
219
220 // Convert size to human-readable string.
221 $.each( modules, function ( i, module ) {
222 module.sizeInBytes = module.size;
223 module.size = humanSize( module.size );
224 } );
225
226 return modules;
227 },
228
229 /**
230 * For each module with styles, count the number of selectors, and
231 * count how many match against some element currently in the DOM.
232 *
233 * @return {Object[]} CSS reports
234 */
235 css: function () {
236 var modules = [];
237
238 $.each( inspect.getLoadedModules(), function ( index, name ) {
239 var css, stats, module = mw.loader.moduleRegistry[ name ];
240
241 try {
242 css = module.style.css.join();
243 } catch ( e ) { return; } // skip
244
245 stats = inspect.auditSelectors( css );
246 modules.push( {
247 module: name,
248 allSelectors: stats.total,
249 matchedSelectors: stats.matched,
250 percentMatched: stats.total !== 0 ?
251 ( stats.matched / stats.total * 100 ).toFixed( 2 ) + '%' : null
252 } );
253 } );
254 sortByProperty( modules, 'allSelectors', true );
255 return modules;
256 },
257
258 /**
259 * Report stats on mw.loader.store: the number of localStorage
260 * cache hits and misses, the number of items purged from the
261 * cache, and the total size of the module blob in localStorage.
262 *
263 * @return {Object[]} Store stats
264 */
265 store: function () {
266 var raw, stats = { enabled: mw.loader.store.enabled };
267 if ( stats.enabled ) {
268 $.extend( stats, mw.loader.store.stats );
269 try {
270 raw = localStorage.getItem( mw.loader.store.getStoreKey() );
271 stats.totalSizeInBytes = $.byteLength( raw );
272 stats.totalSize = humanSize( $.byteLength( raw ) );
273 } catch ( e ) {}
274 }
275 return [ stats ];
276 }
277 },
278
279 /**
280 * Perform a string search across the JavaScript and CSS source code
281 * of all loaded modules and return an array of the names of the
282 * modules that matched.
283 *
284 * @param {string|RegExp} pattern String or regexp to match.
285 * @return {Array} Array of the names of modules that matched.
286 */
287 grep: function ( pattern ) {
288 if ( typeof pattern.test !== 'function' ) {
289 pattern = new RegExp( mw.RegExp.escape( pattern ), 'g' );
290 }
291
292 return $.grep( inspect.getLoadedModules(), function ( moduleName ) {
293 var module = mw.loader.moduleRegistry[ moduleName ];
294
295 // Grep module's JavaScript
296 if ( $.isFunction( module.script ) && pattern.test( module.script.toString() ) ) {
297 return true;
298 }
299
300 // Grep module's CSS
301 if (
302 $.isPlainObject( module.style ) && $.isArray( module.style.css ) &&
303 pattern.test( module.style.css.join( '' ) )
304 ) {
305 // Module's CSS source matches
306 return true;
307 }
308
309 return false;
310 } );
311 }
312 };
313
314 if ( mw.config.get( 'debug' ) ) {
315 mw.log( 'mw.inspect: reports are not available in debug mode.' );
316 }
317
318 mw.inspect = inspect;
319
320 }( mediaWiki, jQuery ) );