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