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