Add 3D filetype for STL files
[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, size;
77
78 if ( module.state !== 'ready' ) {
79 return null;
80 }
81
82 if ( !module.style && !module.script ) {
83 return 0;
84 }
85
86 function getFunctionBody( func ) {
87 return String( func )
88 // To ensure a deterministic result, replace the start of the function
89 // declaration with a fixed string. For example, in Chrome 55, it seems
90 // V8 seemingly-at-random decides to sometimes put a line break between
91 // the opening brace and first statement of the function body. T159751.
92 .replace( /^\s*function\s*\([^)]*\)\s*{\s*/, 'function(){' )
93 .replace( /\s*}\s*$/, '}' );
94 }
95
96 // Based on the load.php response for this module.
97 // For example: `mw.loader.implement("example", function(){}, {"css":[".x{color:red}"]});`
98 // @see mw.loader.store.set().
99 args = [
100 moduleName,
101 module.script,
102 module.style,
103 module.messages,
104 module.templates
105 ];
106 // Trim trailing null or empty object, as load.php would have done.
107 // @see ResourceLoader::makeLoaderImplementScript and ResourceLoader::trimArray.
108 i = args.length;
109 while ( i-- ) {
110 if ( args[ i ] === null || ( $.isPlainObject( args[ i ] ) && $.isEmptyObject( args[ i ] ) ) ) {
111 args.splice( i, 1 );
112 } else {
113 break;
114 }
115 }
116
117 size = 0;
118 for ( i = 0; i < args.length; i++ ) {
119 if ( typeof args[ i ] === 'function' ) {
120 size += $.byteLength( getFunctionBody( args[ i ] ) );
121 } else {
122 size += $.byteLength( JSON.stringify( args[ i ] ) );
123 }
124 }
125
126 return size;
127 },
128
129 /**
130 * Given CSS source, count both the total number of selectors it
131 * contains and the number which match some element in the current
132 * document.
133 *
134 * @param {string} css CSS source
135 * @return {Object} Selector counts
136 * @return {number} return.selectors Total number of selectors
137 * @return {number} return.matched Number of matched selectors
138 */
139 auditSelectors: function ( css ) {
140 var selectors = { total: 0, matched: 0 },
141 style = document.createElement( 'style' );
142
143 style.textContent = css;
144 document.body.appendChild( style );
145 $.each( style.sheet.cssRules, function ( index, rule ) {
146 selectors.total++;
147 // document.querySelector() on prefixed pseudo-elements can throw exceptions
148 // in Firefox and Safari. Ignore these exceptions.
149 // https://bugs.webkit.org/show_bug.cgi?id=149160
150 // https://bugzilla.mozilla.org/show_bug.cgi?id=1204880
151 try {
152 if ( document.querySelector( rule.selectorText ) !== null ) {
153 selectors.matched++;
154 }
155 } catch ( e ) {}
156 } );
157 document.body.removeChild( style );
158 return selectors;
159 },
160
161 /**
162 * Get a list of all loaded ResourceLoader modules.
163 *
164 * @return {Array} List of module names
165 */
166 getLoadedModules: function () {
167 return $.grep( mw.loader.getModuleNames(), function ( module ) {
168 return mw.loader.getState( module ) === 'ready';
169 } );
170 },
171
172 /**
173 * Print tabular data to the console, using console.table, console.log,
174 * or mw.log (in declining order of preference).
175 *
176 * @param {Array} data Tabular data represented as an array of objects
177 * with common properties.
178 */
179 dumpTable: function ( data ) {
180 try {
181 // Bartosz made me put this here.
182 if ( window.opera ) { throw window.opera; }
183 // Use Function.prototype#call to force an exception on Firefox,
184 // which doesn't define console#table but doesn't complain if you
185 // try to invoke it.
186 console.table.call( console, data );
187 return;
188 } catch ( e ) {}
189 try {
190 console.log( JSON.stringify( data, null, 2 ) );
191 return;
192 } catch ( e ) {}
193 mw.log( data );
194 },
195
196 /**
197 * Generate and print one more reports. When invoked with no arguments,
198 * print all reports.
199 *
200 * @param {...string} [reports] Report names to run, or unset to print
201 * all available reports.
202 */
203 runReports: function () {
204 var reports = arguments.length > 0 ?
205 Array.prototype.slice.call( arguments ) :
206 $.map( inspect.reports, function ( v, k ) { return k; } );
207
208 $.each( reports, function ( index, name ) {
209 inspect.dumpTable( inspect.reports[ name ]() );
210 } );
211 },
212
213 /**
214 * @class mw.inspect.reports
215 * @singleton
216 */
217 reports: {
218 /**
219 * Generate a breakdown of all loaded modules and their size in
220 * kilobytes. Modules are ordered from largest to smallest.
221 *
222 * @return {Object[]} Size reports
223 */
224 size: function () {
225 // Map each module to a descriptor object.
226 var modules = $.map( inspect.getLoadedModules(), function ( module ) {
227 return {
228 name: module,
229 size: inspect.getModuleSize( module )
230 };
231 } );
232
233 // Sort module descriptors by size, largest first.
234 sortByProperty( modules, 'size', true );
235
236 // Convert size to human-readable string.
237 $.each( modules, function ( i, module ) {
238 module.sizeInBytes = module.size;
239 module.size = humanSize( module.size );
240 } );
241
242 return modules;
243 },
244
245 /**
246 * For each module with styles, count the number of selectors, and
247 * count how many match against some element currently in the DOM.
248 *
249 * @return {Object[]} CSS reports
250 */
251 css: function () {
252 var modules = [];
253
254 $.each( inspect.getLoadedModules(), function ( index, name ) {
255 var css, stats, module = mw.loader.moduleRegistry[ name ];
256
257 try {
258 css = module.style.css.join();
259 } catch ( e ) { return; } // skip
260
261 stats = inspect.auditSelectors( css );
262 modules.push( {
263 module: name,
264 allSelectors: stats.total,
265 matchedSelectors: stats.matched,
266 percentMatched: stats.total !== 0 ?
267 ( stats.matched / stats.total * 100 ).toFixed( 2 ) + '%' : null
268 } );
269 } );
270 sortByProperty( modules, 'allSelectors', true );
271 return modules;
272 },
273
274 /**
275 * Report stats on mw.loader.store: the number of localStorage
276 * cache hits and misses, the number of items purged from the
277 * cache, and the total size of the module blob in localStorage.
278 *
279 * @return {Object[]} Store stats
280 */
281 store: function () {
282 var raw, stats = { enabled: mw.loader.store.enabled };
283 if ( stats.enabled ) {
284 $.extend( stats, mw.loader.store.stats );
285 try {
286 raw = localStorage.getItem( mw.loader.store.getStoreKey() );
287 stats.totalSizeInBytes = $.byteLength( raw );
288 stats.totalSize = humanSize( $.byteLength( raw ) );
289 } catch ( e ) {}
290 }
291 return [ stats ];
292 }
293 },
294
295 /**
296 * Perform a string search across the JavaScript and CSS source code
297 * of all loaded modules and return an array of the names of the
298 * modules that matched.
299 *
300 * @param {string|RegExp} pattern String or regexp to match.
301 * @return {Array} Array of the names of modules that matched.
302 */
303 grep: function ( pattern ) {
304 if ( typeof pattern.test !== 'function' ) {
305 pattern = new RegExp( mw.RegExp.escape( pattern ), 'g' );
306 }
307
308 return $.grep( inspect.getLoadedModules(), function ( moduleName ) {
309 var module = mw.loader.moduleRegistry[ moduleName ];
310
311 // Grep module's JavaScript
312 if ( $.isFunction( module.script ) && pattern.test( module.script.toString() ) ) {
313 return true;
314 }
315
316 // Grep module's CSS
317 if (
318 $.isPlainObject( module.style ) && Array.isArray( module.style.css ) &&
319 pattern.test( module.style.css.join( '' ) )
320 ) {
321 // Module's CSS source matches
322 return true;
323 }
324
325 return false;
326 } );
327 }
328 };
329
330 if ( mw.config.get( 'debug' ) ) {
331 mw.log( 'mw.inspect: reports are not available in debug mode.' );
332 }
333
334 mw.inspect = inspect;
335
336 }( mediaWiki, jQuery ) );