Debian Codegraph @

resources/src/mediawiki.inspect.js

raw symbols SCIP
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 () {
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 * @classdesc Tools for inspecting page composition and performance.
19 *
20 * @class mediawiki.inspect
21 * @hideconstructor
22 */
23
24 const inspect = mw.inspect,
25 byteLength = require( 'mediawiki.String' ).byteLength,
26 hasOwn = Object.prototype.hasOwnProperty;
27
28 function sortByProperty( array, prop, descending ) {
29 const order = descending ? -1 : 1;
30 return array.sort( ( a, b ) => {
31 if ( a[ prop ] === undefined || b[ prop ] === undefined ) {
32 // Sort undefined to the end, regardless of direction
33 return a[ prop ] !== undefined ? -1 : b[ prop ] !== undefined ? 1 : 0;
34 }
35 return a[ prop ] > b[ prop ] ? order : a[ prop ] < b[ prop ] ? -order : 0;
36 } );
37 }
38
39 function humanSize( bytesInput ) {
40 let bytes = +bytesInput;
41 const units = [ '', ' KiB', ' MiB', ' GiB', ' TiB', ' PiB' ];
42
43 if ( bytes === 0 || isNaN( bytes ) ) {
44 return bytesInput;
45 }
46
47 let i;
48 for ( i = 0; bytes >= 1024; bytes /= 1024 ) {
49 i++;
50 }
51 // Maintain one decimal for KiB and above, but don't
52 // add ".0" for bytes.
53 return bytes.toFixed( i > 0 ? 1 : 0 ) + units[ i ];
54 }
55
56 /**
57 * Return a map of all dependency relationships between loaded modules.
58 *
59 * @return {Object} Maps module names to objects. Each sub-object has
60 * two properties, 'requires' and 'requiredBy'.
61 * @memberof mediawiki.inspect
62 * @method mediawiki.inspect.getDependencyGraph
63 */
64 inspect.getDependencyGraph = function () {
65 const modules = inspect.getLoadedModules(),
66 graph = {};
67
68 modules.forEach( ( moduleName ) => {
69 const dependencies = mw.loader.moduleRegistry[ moduleName ].dependencies || [];
70
71 if ( !hasOwn.call( graph, moduleName ) ) {
72 graph[ moduleName ] = { requiredBy: [] };
73 }
74 graph[ moduleName ].requires = dependencies;
75
76 dependencies.forEach( ( depName ) => {
77 if ( !hasOwn.call( graph, depName ) ) {
78 graph[ depName ] = { requiredBy: [] };
79 }
80 graph[ depName ].requiredBy.push( moduleName );
81 } );
82 } );
83 return graph;
84 };
85
86 /**
87 * Calculate the byte size of a ResourceLoader module.
88 *
89 * @param {string} moduleName The name of the module
90 * @return {number|null} Module size in bytes or null
91 * @memberof mediawiki.inspect
92 * @method mediawiki.inspect.getModuleSize
93 */
94 inspect.getModuleSize = function ( moduleName ) {
95 // We typically receive them from the server through batches from load.php,
96 // or embedded as inline scripts (handled in PHP by ResourceLoader::makeModuleResponse
97 // and ResourceLoader\ClientHtml respectively).
98 //
99 // The module declarator function is stored by mw.loader.implement(), allowing easy
100 // computation of the exact size.
101 const module = mw.loader.moduleRegistry[ moduleName ];
102
103 if ( module.state !== 'ready' ) {
104 return null;
105 }
106 if ( !module.declarator ) {
107 return 0;
108 }
109 return byteLength( module.declarator.toString() );
110 };
111
112 /**
113 * Given CSS source, count both the total number of selectors it
114 * contains and the number which match some element in the current
115 * document.
116 *
117 * @param {string} css CSS source
118 * @return {Object} Selector counts
119 * @return {number} return.selectors Total number of selectors
120 * @return {number} return.matched Number of matched selectors
121 * @memberof mediawiki.inspect
122 * @method mediawiki.inspect.auditSelectors
123 */
124 inspect.auditSelectors = function ( css ) {
125 const selectors = { total: 0, matched: 0 },
126 style = document.createElement( 'style' );
127
128 style.textContent = css;
129 document.body.appendChild( style );
130 const cssRules = style.sheet.cssRules;
131 for ( const index in cssRules ) {
132 const rule = cssRules[ index ];
133 selectors.total++;
134 // document.querySelector() on prefixed pseudo-elements can throw exceptions
135 // in Firefox and Safari. Ignore these exceptions.
136 // https://bugs.webkit.org/show_bug.cgi?id=149160
137 // https://bugzilla.mozilla.org/show_bug.cgi?id=1204880
138 try {
139 if ( document.querySelector( rule.selectorText ) !== null ) {
140 selectors.matched++;
141 }
142 } catch ( e ) {}
143 }
144 document.body.removeChild( style );
145 return selectors;
146 };
147
148 /**
149 * Get a list of all loaded ResourceLoader modules.
150 *
151 * @return {Array} List of module names
152 * @memberof mediawiki.inspect
153 * @method mediawiki.inspect.getLoadedModules
154 */
155 inspect.getLoadedModules = function () {
156 return mw.loader.getModuleNames().filter( ( module ) => mw.loader.getState( module ) === 'ready' );
157 };
158
159 /**
160 * Print tabular data to the console using console.table.
161 *
162 * @param {Array} data Tabular data represented as an array of objects
163 * with common properties.
164 * @memberof mediawiki.inspect
165 * @method mediawiki.inspect.dumpTable
166 */
167 inspect.dumpTable = console.table;
168
169 /**
170 * Generate and print reports.
171 *
172 * When invoked without arguments, prints all available reports.
173 *
174 * @param {...string} [reports] One or more of "size", "css", "store", or "time".
175 * @memberof mediawiki.inspect
176 * @method mediawiki.inspect.runReports
177 */
178 inspect.runReports = function () {
179 const reports = arguments.length > 0 ?
180 Array.prototype.slice.call( arguments ) :
181 Object.keys( inspect.reports );
182
183 reports.forEach( ( name ) => {
184 if ( console.group ) {
185 console.group( 'mw.inspect ' + name + ' report' );
186 } else {
187 console.log( 'mw.inspect ' + name + ' report' );
188 }
189 inspect.dumpTable( inspect.reports[ name ]() );
190 if ( console.group ) {
191 console.groupEnd( 'mw.inspect ' + name + ' report' );
192 }
193 } );
194 };
195
196 /**
197 * Perform a string search across the JavaScript and CSS source code
198 * of all loaded modules and return an array of the names of the
199 * modules that matched.
200 *
201 * @param {string|RegExp} pattern String or regexp to match.
202 * @return {Array} Array of the names of modules that matched.
203 * @memberof mediawiki.inspect
204 * @method mediawiki.inspect.grep
205 */
206 inspect.grep = function ( pattern ) {
207 if ( typeof pattern.test !== 'function' ) {
208
209 pattern = new RegExp( mw.util.escapeRegExp( pattern ), 'g' );
210 }
211
212 return inspect.getLoadedModules().filter( ( moduleName ) => {
213 const module = mw.loader.moduleRegistry[ moduleName ];
214
215 // Grep module's JavaScript
216 if ( typeof module.script === 'function' && pattern.test( module.script.toString() ) ) {
217 return true;
218 }
219
220 // Grep module's CSS
221 if (
222 $.isPlainObject( module.style ) && Array.isArray( module.style.css ) &&
223 pattern.test( module.style.css.join( '' ) )
224 ) {
225 // Module's CSS source matches
226 return true;
227 }
228
229 return false;
230 } );
231 };
232
233 /**
234 * @private
235 * @class mw.inspect.reports
236 * @singleton
237 */
238 inspect.reports = {
239 /**
240 * Generate a breakdown of all loaded modules and their size in
241 * kibibytes. Modules are ordered from largest to smallest.
242 *
243 * @return {Object[]} Size reports
244 */
245 size: function () {
246 // Map each module to a descriptor object.
247 const modules = inspect.getLoadedModules().map( ( module ) => ( {
248 name: module,
249 size: inspect.getModuleSize( module )
250 } ) );
251
252 // Sort module descriptors by size, largest first.
253 sortByProperty( modules, 'size', true );
254
255 // Convert size to human-readable string.
256 modules.forEach( ( module ) => {
257 module.sizeInBytes = module.size;
258 module.size = humanSize( module.size );
259 } );
260
261 return modules;
262 },
263
264 /**
265 * For each module with styles, count the number of selectors, and
266 * count how many match against some element currently in the DOM.
267 *
268 * @return {Object[]} CSS reports
269 */
270 css: function () {
271 const modules = [];
272
273 inspect.getLoadedModules().forEach( ( name ) => {
274 const module = mw.loader.moduleRegistry[ name ];
275
276 let css;
277 try {
278 css = module.style.css.join();
279 } catch ( e ) {
280 // skip
281 return;
282 }
283
284 const stats = inspect.auditSelectors( css );
285 modules.push( {
286 module: name,
287 allSelectors: stats.total,
288 matchedSelectors: stats.matched,
289 percentMatched: stats.total !== 0 ?
290 ( stats.matched / stats.total * 100 ).toFixed( 2 ) + '%' : null
291 } );
292 } );
293 sortByProperty( modules, 'allSelectors', true );
294 return modules;
295 },
296
297 /**
298 * Report stats on mw.loader.store: the number of localStorage
299 * cache hits and misses, the number of items purged from the
300 * cache, and the total size of the module blob in localStorage.
301 *
302 * @return {Object[]} Store stats
303 */
304 store: function () {
305 const stats = { enabled: mw.loader.store.enabled };
306 if ( stats.enabled ) {
307 Object.assign( stats, mw.loader.store.stats );
308 try {
309 const raw = localStorage.getItem( mw.loader.store.key );
310 stats.totalSizeInBytes = byteLength( raw );
311 stats.totalSize = humanSize( byteLength( raw ) );
312 } catch ( e ) {}
313 }
314 return [ stats ];
315 },
316
317 /**
318 * Generate a breakdown of all loaded modules and their time
319 * spent during initialisation (measured in milliseconds).
320 *
321 * This timing data is collected by mw.loader.profiler.
322 *
323 * @return {Object[]} Table rows
324 */
325 time: function () {
326 if ( !mw.loader.profiler ) {
327 mw.log.warn( 'mw.inspect: The time report requires $wgResourceLoaderEnableJSProfiler.' );
328 return [];
329 }
330
331 const modules = inspect.getLoadedModules()
332 .map( ( moduleName ) => mw.loader.profiler.getProfile( moduleName ) )
333 .filter(
334 // Exclude modules that reached "ready" state without involvement from mw.loader.
335 // This is primarily styles-only as loaded via <link rel="stylesheet">.
336 ( perf ) => perf !== null
337 );
338
339 // Sort by total time spent, highest first.
340 sortByProperty( modules, 'total', true );
341
342 // Add human-readable strings
343 modules.forEach( ( module ) => {
344 module.totalInMs = module.total;
345 module.total = module.totalInMs.toLocaleString() + ' ms';
346 } );
347
348 return modules;
349 }
350 };
351
352 if ( mw.config.get( 'debug' ) ) {
353 mw.log( 'mw.inspect: reports are not available in debug mode.' );
354 }
355
356 }() );