Merge "Fix 'Tags' padding to keep it farther from the edge and document the source...
[lhc/web/wiklou.git] / resources / src / startup / mediawiki.js
1 /**
2 * Base library for MediaWiki.
3 *
4 * Exposed globally as `mediaWiki` with `mw` as shortcut.
5 *
6 * @class mw
7 * @alternateClassName mediaWiki
8 * @singleton
9 */
10
11 ( function () {
12 'use strict';
13
14 var mw, StringSet, log,
15 hasOwn = Object.prototype.hasOwnProperty,
16 trackQueue = [];
17
18 /**
19 * FNV132 hash function
20 *
21 * This function implements the 32-bit version of FNV-1.
22 * It is equivalent to hash( 'fnv132', ... ) in PHP, except
23 * its output is base 36 rather than hex.
24 * See <https://en.wikipedia.org/wiki/FNV_hash_function>
25 *
26 * @private
27 * @param {string} str String to hash
28 * @return {string} hash as an seven-character base 36 string
29 */
30 function fnv132( str ) {
31 /* eslint-disable no-bitwise */
32 var hash = 0x811C9DC5,
33 i;
34
35 for ( i = 0; i < str.length; i++ ) {
36 hash += ( hash << 1 ) + ( hash << 4 ) + ( hash << 7 ) + ( hash << 8 ) + ( hash << 24 );
37 hash ^= str.charCodeAt( i );
38 }
39
40 hash = ( hash >>> 0 ).toString( 36 );
41 while ( hash.length < 7 ) {
42 hash = '0' + hash;
43 }
44
45 return hash;
46 /* eslint-enable no-bitwise */
47 }
48
49 function defineFallbacks() {
50 // <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set>
51 StringSet = window.Set || ( function () {
52 /**
53 * @private
54 * @class
55 */
56 function StringSet() {
57 this.set = {};
58 }
59 StringSet.prototype.add = function ( value ) {
60 this.set[ value ] = true;
61 };
62 StringSet.prototype.has = function ( value ) {
63 return hasOwn.call( this.set, value );
64 };
65 return StringSet;
66 }() );
67 }
68
69 /**
70 * Alias property to the global object.
71 *
72 * @private
73 * @static
74 * @member mw.Map
75 * @param {mw.Map} map
76 * @param {string} key
77 * @param {Mixed} value
78 */
79 function setGlobalMapValue( map, key, value ) {
80 map.values[ key ] = value;
81 log.deprecate(
82 window,
83 key,
84 value,
85 // Deprecation notice for mw.config globals (T58550, T72470)
86 map === mw.config && 'Use mw.config instead.'
87 );
88 }
89
90 /**
91 * Log a message to window.console, if possible.
92 *
93 * Useful to force logging of some errors that are otherwise hard to detect (i.e., this logs
94 * also in production mode). Gets console references in each invocation instead of caching the
95 * reference, so that debugging tools loaded later are supported (e.g. Firebug Lite in IE).
96 *
97 * @private
98 * @param {string} topic Stream name passed by mw.track
99 * @param {Object} data Data passed by mw.track
100 * @param {Error} [data.exception]
101 * @param {string} data.source Error source
102 * @param {string} [data.module] Name of module which caused the error
103 */
104 function logError( topic, data ) {
105 /* eslint-disable no-console */
106 var msg,
107 e = data.exception,
108 source = data.source,
109 module = data.module,
110 console = window.console;
111
112 if ( console && console.log ) {
113 msg = ( e ? 'Exception' : 'Error' ) + ' in ' + source;
114 if ( module ) {
115 msg += ' in module ' + module;
116 }
117 msg += ( e ? ':' : '.' );
118 console.log( msg );
119
120 // If we have an exception object, log it to the warning channel to trigger
121 // proper stacktraces in browsers that support it.
122 if ( e && console.warn ) {
123 console.warn( e );
124 }
125 }
126 /* eslint-enable no-console */
127 }
128
129 /**
130 * Create an object that can be read from or written to via methods that allow
131 * interaction both with single and multiple properties at once.
132 *
133 * @private
134 * @class mw.Map
135 *
136 * @constructor
137 * @param {boolean} [global=false] Whether to synchronise =values to the global
138 * window object (for backwards-compatibility with mw.config; T72470). Values are
139 * copied in one direction only. Changes to globals do not reflect in the map.
140 */
141 function Map( global ) {
142 this.values = {};
143 if ( global === true ) {
144 // Override #set to also set the global variable
145 this.set = function ( selection, value ) {
146 var s;
147 if ( arguments.length > 1 ) {
148 if ( typeof selection !== 'string' ) {
149 return false;
150 }
151 setGlobalMapValue( this, selection, value );
152 return true;
153 }
154 if ( typeof selection === 'object' ) {
155 for ( s in selection ) {
156 setGlobalMapValue( this, s, selection[ s ] );
157 }
158 return true;
159 }
160 return false;
161 };
162 }
163 }
164
165 Map.prototype = {
166 constructor: Map,
167
168 /**
169 * Get the value of one or more keys.
170 *
171 * If called with no arguments, all values are returned.
172 *
173 * @param {string|Array} [selection] Key or array of keys to retrieve values for.
174 * @param {Mixed} [fallback=null] Value for keys that don't exist.
175 * @return {Mixed|Object|null} If selection was a string, returns the value,
176 * If selection was an array, returns an object of key/values.
177 * If no selection is passed, a new object with all key/values is returned.
178 */
179 get: function ( selection, fallback ) {
180 var results, i;
181 fallback = arguments.length > 1 ? fallback : null;
182
183 if ( Array.isArray( selection ) ) {
184 results = {};
185 for ( i = 0; i < selection.length; i++ ) {
186 if ( typeof selection[ i ] === 'string' ) {
187 results[ selection[ i ] ] = hasOwn.call( this.values, selection[ i ] ) ?
188 this.values[ selection[ i ] ] :
189 fallback;
190 }
191 }
192 return results;
193 }
194
195 if ( typeof selection === 'string' ) {
196 return hasOwn.call( this.values, selection ) ?
197 this.values[ selection ] :
198 fallback;
199 }
200
201 if ( selection === undefined ) {
202 results = {};
203 for ( i in this.values ) {
204 results[ i ] = this.values[ i ];
205 }
206 return results;
207 }
208
209 // Invalid selection key
210 return fallback;
211 },
212
213 /**
214 * Set one or more key/value pairs.
215 *
216 * @param {string|Object} selection Key to set value for, or object mapping keys to values
217 * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
218 * @return {boolean} True on success, false on failure
219 */
220 set: function ( selection, value ) {
221 var s;
222 // Use `arguments.length` because `undefined` is also a valid value.
223 if ( arguments.length > 1 ) {
224 if ( typeof selection !== 'string' ) {
225 return false;
226 }
227 this.values[ selection ] = value;
228 return true;
229 }
230 if ( typeof selection === 'object' ) {
231 for ( s in selection ) {
232 this.values[ s ] = selection[ s ];
233 }
234 return true;
235 }
236 return false;
237 },
238
239 /**
240 * Check if one or more keys exist.
241 *
242 * @param {Mixed} selection Key or array of keys to check
243 * @return {boolean} True if the key(s) exist
244 */
245 exists: function ( selection ) {
246 var i;
247 if ( Array.isArray( selection ) ) {
248 for ( i = 0; i < selection.length; i++ ) {
249 if ( typeof selection[ i ] !== 'string' || !hasOwn.call( this.values, selection[ i ] ) ) {
250 return false;
251 }
252 }
253 return true;
254 }
255 return typeof selection === 'string' && hasOwn.call( this.values, selection );
256 }
257 };
258
259 defineFallbacks();
260
261 /* eslint-disable no-console */
262 log = ( function () {
263 /**
264 * Write a verbose message to the browser's console in debug mode.
265 *
266 * This method is mainly intended for verbose logging. It is a no-op in production mode.
267 * In ResourceLoader debug mode, it will use the browser's console if available, with
268 * fallback to creating a console interface in the DOM and logging messages there.
269 *
270 * See {@link mw.log} for other logging methods.
271 *
272 * @member mw
273 * @param {...string} msg Messages to output to console.
274 */
275 var log = function () {},
276 console = window.console;
277
278 // Note: Keep list of methods in sync with restoration in mediawiki.log.js
279 // when adding or removing mw.log methods below!
280
281 /**
282 * Collection of methods to help log messages to the console.
283 *
284 * @class mw.log
285 * @singleton
286 */
287
288 /**
289 * Write a message to the browser console's warning channel.
290 *
291 * This method is a no-op in browsers that don't implement the Console API.
292 *
293 * @param {...string} msg Messages to output to console
294 */
295 log.warn = console && console.warn && Function.prototype.bind ?
296 Function.prototype.bind.call( console.warn, console ) :
297 function () {};
298
299 /**
300 * Write a message to the browser console's error channel.
301 *
302 * Most browsers also print a stacktrace when calling this method if the
303 * argument is an Error object.
304 *
305 * This method is a no-op in browsers that don't implement the Console API.
306 *
307 * @since 1.26
308 * @param {...Mixed} msg Messages to output to console
309 */
310 log.error = console && console.error && Function.prototype.bind ?
311 Function.prototype.bind.call( console.error, console ) :
312 function () {};
313
314 /**
315 * Create a property on a host object that, when accessed, will produce
316 * a deprecation warning in the console.
317 *
318 * @param {Object} obj Host object of deprecated property
319 * @param {string} key Name of property to create in `obj`
320 * @param {Mixed} val The value this property should return when accessed
321 * @param {string} [msg] Optional text to include in the deprecation message
322 * @param {string} [logName=key] Optional custom name for the feature.
323 * This is used instead of `key` in the message and `mw.deprecate` tracking.
324 */
325 log.deprecate = !Object.defineProperty ? function ( obj, key, val ) {
326 obj[ key ] = val;
327 } : function ( obj, key, val, msg, logName ) {
328 var logged = new StringSet();
329 logName = logName || key;
330 msg = 'Use of "' + logName + '" is deprecated.' + ( msg ? ( ' ' + msg ) : '' );
331 function uniqueTrace() {
332 var trace = new Error().stack;
333 if ( logged.has( trace ) ) {
334 return false;
335 }
336 logged.add( trace );
337 return true;
338 }
339 // Support: Safari 5.0
340 // Throws "not supported on DOM Objects" for Node or Element objects (incl. document)
341 // Safari 4.0 doesn't have this method, and it was fixed in Safari 5.1.
342 try {
343 Object.defineProperty( obj, key, {
344 configurable: true,
345 enumerable: true,
346 get: function () {
347 if ( uniqueTrace() ) {
348 mw.track( 'mw.deprecate', logName );
349 mw.log.warn( msg );
350 }
351 return val;
352 },
353 set: function ( newVal ) {
354 if ( uniqueTrace() ) {
355 mw.track( 'mw.deprecate', logName );
356 mw.log.warn( msg );
357 }
358 val = newVal;
359 }
360 } );
361 } catch ( err ) {
362 obj[ key ] = val;
363 }
364 };
365
366 return log;
367 }() );
368 /* eslint-enable no-console */
369
370 /**
371 * @class mw
372 */
373 mw = {
374 redefineFallbacksForTest: function () {
375 if ( !window.QUnit ) {
376 throw new Error( 'Reset not allowed outside unit tests' );
377 }
378 defineFallbacks();
379 },
380
381 /**
382 * Get the current time, measured in milliseconds since January 1, 1970 (UTC).
383 *
384 * On browsers that implement the Navigation Timing API, this function will produce floating-point
385 * values with microsecond precision that are guaranteed to be monotonic. On all other browsers,
386 * it will fall back to using `Date`.
387 *
388 * @return {number} Current time
389 */
390 now: ( function () {
391 var perf = window.performance,
392 navStart = perf && perf.timing && perf.timing.navigationStart;
393 return navStart && typeof perf.now === 'function' ?
394 function () { return navStart + perf.now(); } :
395 function () { return Date.now(); };
396 }() ),
397
398 /**
399 * List of all analytic events emitted so far.
400 *
401 * @private
402 * @property {Array}
403 */
404 trackQueue: trackQueue,
405
406 track: function ( topic, data ) {
407 trackQueue.push( { topic: topic, timeStamp: mw.now(), data: data } );
408 // The base module extends this method to fire events here
409 },
410
411 /**
412 * Track an early error event via mw.track and send it to the window console.
413 *
414 * @private
415 * @param {string} topic Topic name
416 * @param {Object} data Data describing the event, encoded as an object; see mw#logError
417 */
418 trackError: function ( topic, data ) {
419 mw.track( topic, data );
420 logError( topic, data );
421 },
422
423 // Expose Map constructor
424 Map: Map,
425
426 /**
427 * Map of configuration values.
428 *
429 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
430 * on mediawiki.org.
431 *
432 * If `$wgLegacyJavaScriptGlobals` is true, this Map will add its values to the
433 * global `window` object.
434 *
435 * @property {mw.Map} config
436 */
437 // Dummy placeholder later assigned in ResourceLoaderStartUpModule
438 config: null,
439
440 /**
441 * Empty object for third-party libraries, for cases where you don't
442 * want to add a new global, or the global is bad and needs containment
443 * or wrapping.
444 *
445 * @property
446 */
447 libs: {},
448
449 /**
450 * Access container for deprecated functionality that can be moved from
451 * from their legacy location and attached to this object (e.g. a global
452 * function that is deprecated and as stop-gap can be exposed through here).
453 *
454 * This was reserved for future use but never ended up being used.
455 *
456 * @deprecated since 1.22 Let deprecated identifiers keep their original name
457 * and use mw.log#deprecate to create an access container for tracking.
458 * @property
459 */
460 legacy: {},
461
462 /**
463 * Store for messages.
464 *
465 * @property {mw.Map}
466 */
467 messages: new Map(),
468
469 /**
470 * Store for templates associated with a module.
471 *
472 * @property {mw.Map}
473 */
474 templates: new Map(),
475
476 // Expose mw.log
477 log: log,
478
479 /**
480 * Client for ResourceLoader server end point.
481 *
482 * This client is in charge of maintaining the module registry and state
483 * machine, initiating network (batch) requests for loading modules, as
484 * well as dependency resolution and execution of source code.
485 *
486 * For more information, refer to
487 * <https://www.mediawiki.org/wiki/ResourceLoader/Features>
488 *
489 * @class mw.loader
490 * @singleton
491 */
492 loader: ( function () {
493
494 /**
495 * Fired via mw.track on various resource loading errors.
496 *
497 * @event resourceloader_exception
498 * @param {Error|Mixed} e The error that was thrown. Almost always an Error
499 * object, but in theory module code could manually throw something else, and that
500 * might also end up here.
501 * @param {string} [module] Name of the module which caused the error. Omitted if the
502 * error is not module-related or the module cannot be easily identified due to
503 * batched handling.
504 * @param {string} source Source of the error. Possible values:
505 *
506 * - style: stylesheet error (only affects old IE where a special style loading method
507 * is used)
508 * - load-callback: exception thrown by user callback
509 * - module-execute: exception thrown by module code
510 * - resolve: failed to sort dependencies for a module in mw.loader.load
511 * - store-eval: could not evaluate module code cached in localStorage
512 * - store-localstorage-init: localStorage or JSON parse error in mw.loader.store.init
513 * - store-localstorage-json: JSON conversion error in mw.loader.store.set
514 * - store-localstorage-update: localStorage or JSON conversion error in mw.loader.store.update
515 */
516
517 /**
518 * Fired via mw.track on resource loading error conditions.
519 *
520 * @event resourceloader_assert
521 * @param {string} source Source of the error. Possible values:
522 *
523 * - bug-T59567: failed to cache script due to an Opera function -> string conversion
524 * bug; see <https://phabricator.wikimedia.org/T59567> for details
525 */
526
527 /**
528 * Mapping of registered modules.
529 *
530 * See #implement and #execute for exact details on support for script, style and messages.
531 *
532 * Format:
533 *
534 * {
535 * 'moduleName': {
536 * // From mw.loader.register()
537 * 'version': '########' (hash)
538 * 'dependencies': ['required.foo', 'bar.also', ...]
539 * 'group': 'somegroup', (or) null
540 * 'source': 'local', (or) 'anotherwiki'
541 * 'skip': 'return !!window.Example', (or) null
542 * 'module': export Object
543 *
544 * // Set from execute() or mw.loader.state()
545 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error', or 'missing'
546 *
547 * // Optionally added at run-time by mw.loader.implement()
548 * 'skipped': true
549 * 'script': closure, array of urls, or string
550 * 'style': { ... } (see #execute)
551 * 'messages': { 'key': 'value', ... }
552 * }
553 * }
554 *
555 * State machine:
556 *
557 * - `registered`:
558 * The module is known to the system but not yet required.
559 * Meta data is registered via mw.loader#register. Calls to that method are
560 * generated server-side by the startup module.
561 * - `loading`:
562 * The module was required through mw.loader (either directly or as dependency of
563 * another module). The client will fetch module contents from the server.
564 * The contents are then stashed in the registry via mw.loader#implement.
565 * - `loaded`:
566 * The module has been loaded from the server and stashed via mw.loader#implement.
567 * If the module has no more dependencies in-flight, the module will be executed
568 * immediately. Otherwise execution is deferred, controlled via #handlePending.
569 * - `executing`:
570 * The module is being executed.
571 * - `ready`:
572 * The module has been successfully executed.
573 * - `error`:
574 * The module (or one of its dependencies) produced an error during execution.
575 * - `missing`:
576 * The module was registered client-side and requested, but the server denied knowledge
577 * of the module's existence.
578 *
579 * @property
580 * @private
581 */
582 var registry = {},
583 // Mapping of sources, keyed by source-id, values are strings.
584 //
585 // Format:
586 //
587 // {
588 // 'sourceId': 'http://example.org/w/load.php'
589 // }
590 //
591 sources = {},
592
593 // For queueModuleScript()
594 handlingPendingRequests = false,
595 pendingRequests = [],
596
597 // List of modules to be loaded
598 queue = [],
599
600 /**
601 * List of callback jobs waiting for modules to be ready.
602 *
603 * Jobs are created by #enqueue() and run by #handlePending().
604 *
605 * Typically when a job is created for a module, the job's dependencies contain
606 * both the required module and all its recursive dependencies.
607 *
608 * Format:
609 *
610 * {
611 * 'dependencies': [ module names ],
612 * 'ready': Function callback
613 * 'error': Function callback
614 * }
615 *
616 * @property {Object[]} jobs
617 * @private
618 */
619 jobs = [],
620
621 /**
622 * For #addEmbeddedCSS() and #addLink()
623 *
624 * @private
625 * @property {HTMLElement|null} marker
626 */
627 marker = document.querySelector( 'meta[name="ResourceLoaderDynamicStyles"]' ),
628
629 // For addEmbeddedCSS()
630 cssBuffer = '',
631 cssBufferTimer = null,
632 cssCallbacks = [],
633 rAF = window.requestAnimationFrame || setTimeout;
634
635 /**
636 * Create a new style element and add it to the DOM.
637 *
638 * @private
639 * @param {string} text CSS text
640 * @param {Node|null} [nextNode] The element where the style tag
641 * should be inserted before
642 * @return {HTMLElement} Reference to the created style element
643 */
644 function newStyleTag( text, nextNode ) {
645 var el = document.createElement( 'style' );
646 el.appendChild( document.createTextNode( text ) );
647 if ( nextNode && nextNode.parentNode ) {
648 nextNode.parentNode.insertBefore( el, nextNode );
649 } else {
650 document.head.appendChild( el );
651 }
652 return el;
653 }
654
655 /**
656 * Add a bit of CSS text to the current browser page.
657 *
658 * The CSS will be appended to an existing ResourceLoader-created `<style>` tag
659 * or create a new one based on whether the given `cssText` is safe for extension.
660 *
661 * @private
662 * @param {string} [cssText=cssBuffer] If called without cssText,
663 * the internal buffer will be inserted instead.
664 * @param {Function} [callback]
665 */
666 function addEmbeddedCSS( cssText, callback ) {
667 function fireCallbacks() {
668 var i,
669 oldCallbacks = cssCallbacks;
670 // Reset cssCallbacks variable so it's not polluted by any calls to
671 // addEmbeddedCSS() from one of the callbacks (T105973)
672 cssCallbacks = [];
673 for ( i = 0; i < oldCallbacks.length; i++ ) {
674 oldCallbacks[ i ]();
675 }
676 }
677
678 if ( callback ) {
679 cssCallbacks.push( callback );
680 }
681
682 // Yield once before creating the <style> tag. This lets multiple stylesheets
683 // accumulate into one buffer, allowing us to reduce how often new stylesheets
684 // are inserted in the browser. Appending a stylesheet and waiting for the
685 // browser to repaint is fairly expensive. (T47810)
686 if ( cssText ) {
687 // Don't extend the buffer if the item needs its own stylesheet.
688 // Keywords like `@import` are only valid at the start of a stylesheet (T37562).
689 if ( !cssBuffer || cssText.slice( 0, '@import'.length ) !== '@import' ) {
690 // Linebreak for somewhat distinguishable sections
691 cssBuffer += '\n' + cssText;
692 if ( !cssBufferTimer ) {
693 cssBufferTimer = rAF( function () {
694 // Wrap in anonymous function that takes no arguments
695 // Support: Firefox < 13
696 // Firefox 12 has non-standard behaviour of passing a number
697 // as first argument to a setTimeout callback.
698 // http://benalman.com/news/2009/07/the-mysterious-firefox-settime/
699 addEmbeddedCSS();
700 } );
701 }
702 return;
703 }
704
705 // This is a scheduled flush for the buffer
706 } else {
707 cssBufferTimer = null;
708 cssText = cssBuffer;
709 cssBuffer = '';
710 }
711
712 newStyleTag( cssText, marker );
713
714 fireCallbacks();
715 }
716
717 /**
718 * @private
719 * @param {Array} modules List of module names
720 * @return {string} Hash of concatenated version hashes.
721 */
722 function getCombinedVersion( modules ) {
723 var hashes = modules.map( function ( module ) {
724 return registry[ module ].version;
725 } );
726 return fnv132( hashes.join( '' ) );
727 }
728
729 /**
730 * Determine whether all dependencies are in state 'ready', which means we may
731 * execute the module or job now.
732 *
733 * @private
734 * @param {Array} modules Names of modules to be checked
735 * @return {boolean} True if all modules are in state 'ready', false otherwise
736 */
737 function allReady( modules ) {
738 var i;
739 for ( i = 0; i < modules.length; i++ ) {
740 if ( mw.loader.getState( modules[ i ] ) !== 'ready' ) {
741 return false;
742 }
743 }
744 return true;
745 }
746
747 /**
748 * Determine whether all dependencies are in state 'ready', which means we may
749 * execute the module or job now.
750 *
751 * @private
752 * @param {Array} modules Names of modules to be checked
753 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
754 */
755 function anyFailed( modules ) {
756 var i, state;
757 for ( i = 0; i < modules.length; i++ ) {
758 state = mw.loader.getState( modules[ i ] );
759 if ( state === 'error' || state === 'missing' ) {
760 return true;
761 }
762 }
763 return false;
764 }
765
766 /**
767 * A module has entered state 'ready', 'error', or 'missing'. Automatically update
768 * pending jobs and modules that depend upon this module. If the given module failed,
769 * propagate the 'error' state up the dependency tree. Otherwise, go ahead and execute
770 * all jobs/modules now having their dependencies satisfied.
771 *
772 * Jobs that depend on a failed module, will have their error callback ran (if any).
773 *
774 * @private
775 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
776 */
777 function handlePending( module ) {
778 var j, job, hasErrors, m, stateChange;
779
780 if ( registry[ module ].state === 'error' || registry[ module ].state === 'missing' ) {
781 // If the current module failed, mark all dependent modules also as failed.
782 // Iterate until steady-state to propagate the error state upwards in the
783 // dependency tree.
784 do {
785 stateChange = false;
786 for ( m in registry ) {
787 if ( registry[ m ].state !== 'error' && registry[ m ].state !== 'missing' ) {
788 if ( anyFailed( registry[ m ].dependencies ) ) {
789 registry[ m ].state = 'error';
790 stateChange = true;
791 }
792 }
793 }
794 } while ( stateChange );
795 }
796
797 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
798 for ( j = 0; j < jobs.length; j++ ) {
799 hasErrors = anyFailed( jobs[ j ].dependencies );
800 if ( hasErrors || allReady( jobs[ j ].dependencies ) ) {
801 // All dependencies satisfied, or some have errors
802 job = jobs[ j ];
803 jobs.splice( j, 1 );
804 j -= 1;
805 try {
806 if ( hasErrors ) {
807 if ( typeof job.error === 'function' ) {
808 job.error( new Error( 'Module ' + module + ' has failed dependencies' ), [ module ] );
809 }
810 } else {
811 if ( typeof job.ready === 'function' ) {
812 job.ready();
813 }
814 }
815 } catch ( e ) {
816 // A user-defined callback raised an exception.
817 // Swallow it to protect our state machine!
818 mw.trackError( 'resourceloader.exception', {
819 exception: e,
820 module: module,
821 source: 'load-callback'
822 } );
823 }
824 }
825 }
826
827 if ( registry[ module ].state === 'ready' ) {
828 // The current module became 'ready'. Set it in the module store, and recursively execute all
829 // dependent modules that are loaded and now have all dependencies satisfied.
830 mw.loader.store.set( module, registry[ module ] );
831 for ( m in registry ) {
832 if ( registry[ m ].state === 'loaded' && allReady( registry[ m ].dependencies ) ) {
833 // eslint-disable-next-line no-use-before-define
834 execute( m );
835 }
836 }
837 }
838 }
839
840 /**
841 * Resolve dependencies and detect circular references.
842 *
843 * @private
844 * @param {string} module Name of the top-level module whose dependencies shall be
845 * resolved and sorted.
846 * @param {Array} resolved Returns a topological sort of the given module and its
847 * dependencies, such that later modules depend on earlier modules. The array
848 * contains the module names. If the array contains already some module names,
849 * this function appends its result to the pre-existing array.
850 * @param {StringSet} [unresolved] Used to track the current dependency
851 * chain, and to report loops in the dependency graph.
852 * @throws {Error} If any unregistered module or a dependency loop is encountered
853 */
854 function sortDependencies( module, resolved, unresolved ) {
855 var i, deps, skip;
856
857 if ( !hasOwn.call( registry, module ) ) {
858 throw new Error( 'Unknown dependency: ' + module );
859 }
860
861 if ( registry[ module ].skip !== null ) {
862 // eslint-disable-next-line no-new-func
863 skip = new Function( registry[ module ].skip );
864 registry[ module ].skip = null;
865 if ( skip() ) {
866 registry[ module ].skipped = true;
867 registry[ module ].dependencies = [];
868 registry[ module ].state = 'ready';
869 handlePending( module );
870 return;
871 }
872 }
873
874 if ( resolved.indexOf( module ) !== -1 ) {
875 // Module already resolved; nothing to do
876 return;
877 }
878 // Create unresolved if not passed in
879 if ( !unresolved ) {
880 unresolved = new StringSet();
881 }
882 // Tracks down dependencies
883 deps = registry[ module ].dependencies;
884 for ( i = 0; i < deps.length; i++ ) {
885 if ( resolved.indexOf( deps[ i ] ) === -1 ) {
886 if ( unresolved.has( deps[ i ] ) ) {
887 throw new Error(
888 'Circular reference detected: ' + module + ' -> ' + deps[ i ]
889 );
890 }
891
892 unresolved.add( module );
893 sortDependencies( deps[ i ], resolved, unresolved );
894 }
895 }
896 resolved.push( module );
897 }
898
899 /**
900 * Get names of module that a module depends on, in their proper dependency order.
901 *
902 * @private
903 * @param {string[]} modules Array of string module names
904 * @return {Array} List of dependencies, including 'module'.
905 * @throws {Error} If an unregistered module or a dependency loop is encountered
906 */
907 function resolve( modules ) {
908 var i, resolved = [];
909 for ( i = 0; i < modules.length; i++ ) {
910 sortDependencies( modules[ i ], resolved );
911 }
912 return resolved;
913 }
914
915 /**
916 * Like #resolve(), except it will silently ignore modules that
917 * are missing or have missing dependencies.
918 *
919 * @private
920 * @param {string[]} modules Array of string module names
921 * @return {Array} List of dependencies.
922 */
923 function resolveStubbornly( modules ) {
924 var i, saved, resolved = [];
925 for ( i = 0; i < modules.length; i++ ) {
926 saved = resolved.slice();
927 try {
928 sortDependencies( modules[ i ], resolved );
929 } catch ( err ) {
930 // This module is unknown or has unknown dependencies.
931 // Undo any incomplete resolutions made and keep going.
932 resolved = saved;
933 mw.trackError( 'resourceloader.exception', {
934 exception: err,
935 source: 'resolve'
936 } );
937 }
938 }
939 return resolved;
940 }
941
942 /**
943 * Load and execute a script.
944 *
945 * @private
946 * @param {string} src URL to script, will be used as the src attribute in the script tag
947 * @param {Function} [callback] Callback to run after request resolution
948 */
949 function addScript( src, callback ) {
950 var script = document.createElement( 'script' );
951 script.src = src;
952 script.onload = script.onerror = function () {
953 if ( script.parentNode ) {
954 script.parentNode.removeChild( script );
955 }
956 script = null;
957 if ( callback ) {
958 callback();
959 callback = null;
960 }
961 };
962 document.head.appendChild( script );
963 }
964
965 /**
966 * Queue the loading and execution of a script for a particular module.
967 *
968 * @private
969 * @param {string} src URL of the script
970 * @param {string} moduleName Name of currently executing module
971 * @param {Function} callback Callback to run after addScript() resolution
972 */
973 function queueModuleScript( src, moduleName, callback ) {
974 pendingRequests.push( function () {
975 if ( hasOwn.call( registry, moduleName ) ) {
976 // Emulate runScript() part of execute()
977 window.require = mw.loader.require;
978 window.module = registry[ moduleName ].module;
979 }
980 addScript( src, function () {
981 // 'module.exports' should not persist after the file is executed to
982 // avoid leakage to unrelated code. 'require' should be kept, however,
983 // as asynchronous access to 'require' is allowed and expected. (T144879)
984 delete window.module;
985 callback();
986 // Start the next one (if any)
987 if ( pendingRequests[ 0 ] ) {
988 pendingRequests.shift()();
989 } else {
990 handlingPendingRequests = false;
991 }
992 } );
993 } );
994 if ( !handlingPendingRequests && pendingRequests[ 0 ] ) {
995 handlingPendingRequests = true;
996 pendingRequests.shift()();
997 }
998 }
999
1000 /**
1001 * Utility function for execute()
1002 *
1003 * @ignore
1004 * @param {string} [media] Media attribute
1005 * @param {string} url URL
1006 */
1007 function addLink( media, url ) {
1008 var el = document.createElement( 'link' );
1009
1010 el.rel = 'stylesheet';
1011 if ( media && media !== 'all' ) {
1012 el.media = media;
1013 }
1014 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1015 // see #addEmbeddedCSS, T33676, T43331, and T49277 for details.
1016 el.href = url;
1017
1018 if ( marker && marker.parentNode ) {
1019 marker.parentNode.insertBefore( el, marker );
1020 } else {
1021 document.head.appendChild( el );
1022 }
1023 }
1024
1025 /**
1026 * @private
1027 * @param {string} code JavaScript code
1028 */
1029 function domEval( code ) {
1030 var script = document.createElement( 'script' );
1031 script.text = code;
1032 document.head.appendChild( script );
1033 script.parentNode.removeChild( script );
1034 }
1035
1036 /**
1037 * Add one or more modules to the module load queue.
1038 *
1039 * See also #work().
1040 *
1041 * @private
1042 * @param {string|string[]} dependencies Module name or array of string module names
1043 * @param {Function} [ready] Callback to execute when all dependencies are ready
1044 * @param {Function} [error] Callback to execute when any dependency fails
1045 */
1046 function enqueue( dependencies, ready, error ) {
1047 // Allow calling by single module name
1048 if ( typeof dependencies === 'string' ) {
1049 dependencies = [ dependencies ];
1050 }
1051
1052 if ( allReady( dependencies ) ) {
1053 // Run ready immediately
1054 if ( ready !== undefined ) {
1055 ready();
1056 }
1057
1058 return;
1059 }
1060
1061 if ( anyFailed( dependencies ) ) {
1062 if ( error !== undefined ) {
1063 // Execute error immediately if any dependencies have errors
1064 error(
1065 new Error( 'One or more dependencies failed to load' ),
1066 dependencies
1067 );
1068 }
1069
1070 return;
1071 }
1072
1073 // Not all dependencies are ready, add to the load queue...
1074
1075 // Add ready and error callbacks if they were given
1076 if ( ready !== undefined || error !== undefined ) {
1077 jobs.push( {
1078 // Narrow down the list to modules that are worth waiting for
1079 dependencies: dependencies.filter( function ( module ) {
1080 var state = mw.loader.getState( module );
1081 return state === 'registered' || state === 'loaded' || state === 'loading' || state === 'executing';
1082 } ),
1083 ready: ready,
1084 error: error
1085 } );
1086 }
1087
1088 dependencies.forEach( function ( module ) {
1089 var state = mw.loader.getState( module );
1090 // Only queue modules that are still in the initial 'registered' state
1091 // (not ones already loading, ready or error).
1092 if ( state === 'registered' && queue.indexOf( module ) === -1 ) {
1093 // Private modules must be embedded in the page. Don't bother queuing
1094 // these as the server will deny them anyway (T101806).
1095 if ( registry[ module ].group === 'private' ) {
1096 registry[ module ].state = 'error';
1097 handlePending( module );
1098 return;
1099 }
1100 queue.push( module );
1101 }
1102 } );
1103
1104 mw.loader.work();
1105 }
1106
1107 /**
1108 * Executes a loaded module, making it ready to use
1109 *
1110 * @private
1111 * @param {string} module Module name to execute
1112 */
1113 function execute( module ) {
1114 var key, value, media, i, urls, cssHandle, checkCssHandles, runScript,
1115 cssHandlesRegistered = false;
1116
1117 if ( !hasOwn.call( registry, module ) ) {
1118 throw new Error( 'Module has not been registered yet: ' + module );
1119 }
1120 if ( registry[ module ].state !== 'loaded' ) {
1121 throw new Error( 'Module in state "' + registry[ module ].state + '" may not be executed: ' + module );
1122 }
1123
1124 registry[ module ].state = 'executing';
1125
1126 runScript = function () {
1127 var script, markModuleReady, nestedAddScript;
1128
1129 script = registry[ module ].script;
1130 markModuleReady = function () {
1131 registry[ module ].state = 'ready';
1132 handlePending( module );
1133 };
1134 nestedAddScript = function ( arr, callback, i ) {
1135 // Recursively call queueModuleScript() in its own callback
1136 // for each element of arr.
1137 if ( i >= arr.length ) {
1138 // We're at the end of the array
1139 callback();
1140 return;
1141 }
1142
1143 queueModuleScript( arr[ i ], module, function () {
1144 nestedAddScript( arr, callback, i + 1 );
1145 } );
1146 };
1147
1148 try {
1149 if ( Array.isArray( script ) ) {
1150 nestedAddScript( script, markModuleReady, 0 );
1151 } else if ( typeof script === 'function' ) {
1152 // Pass jQuery twice so that the signature of the closure which wraps
1153 // the script can bind both '$' and 'jQuery'.
1154 script( window.$, window.$, mw.loader.require, registry[ module ].module );
1155 markModuleReady();
1156
1157 } else if ( typeof script === 'string' ) {
1158 // Site and user modules are legacy scripts that run in the global scope.
1159 // This is transported as a string instead of a function to avoid needing
1160 // to use string manipulation to undo the function wrapper.
1161 domEval( script );
1162 markModuleReady();
1163
1164 } else {
1165 // Module without script
1166 markModuleReady();
1167 }
1168 } catch ( e ) {
1169 // Use mw.track instead of mw.log because these errors are common in production mode
1170 // (e.g. undefined variable), and mw.log is only enabled in debug mode.
1171 registry[ module ].state = 'error';
1172 mw.trackError( 'resourceloader.exception', {
1173 exception: e, module:
1174 module, source: 'module-execute'
1175 } );
1176 handlePending( module );
1177 }
1178 };
1179
1180 // Add localizations to message system
1181 if ( registry[ module ].messages ) {
1182 mw.messages.set( registry[ module ].messages );
1183 }
1184
1185 // Initialise templates
1186 if ( registry[ module ].templates ) {
1187 mw.templates.set( module, registry[ module ].templates );
1188 }
1189
1190 // Make sure we don't run the scripts until all stylesheet insertions have completed.
1191 ( function () {
1192 var pending = 0;
1193 checkCssHandles = function () {
1194 var ex, dependencies;
1195 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
1196 // one of the cssHandles is fired while we're still creating more handles.
1197 if ( cssHandlesRegistered && pending === 0 && runScript ) {
1198 if ( module === 'user' ) {
1199 // Implicit dependency on the site module. Not real dependency because
1200 // it should run after 'site' regardless of whether it succeeds or fails.
1201 // Note: This is a simplified version of mw.loader.using(), inlined here
1202 // as using() depends on jQuery (T192623).
1203 try {
1204 dependencies = resolve( [ 'site' ] );
1205 } catch ( e ) {
1206 ex = e;
1207 runScript();
1208 }
1209 if ( ex === undefined ) {
1210 enqueue( dependencies, runScript, runScript );
1211 }
1212 } else {
1213 runScript();
1214 }
1215 runScript = undefined; // Revoke
1216 }
1217 };
1218 cssHandle = function () {
1219 var check = checkCssHandles;
1220 pending++;
1221 return function () {
1222 if ( check ) {
1223 pending--;
1224 check();
1225 check = undefined; // Revoke
1226 }
1227 };
1228 };
1229 }() );
1230
1231 // Process styles (see also mw.loader.implement)
1232 // * back-compat: { <media>: css }
1233 // * back-compat: { <media>: [url, ..] }
1234 // * { "css": [css, ..] }
1235 // * { "url": { <media>: [url, ..] } }
1236 if ( registry[ module ].style ) {
1237 for ( key in registry[ module ].style ) {
1238 value = registry[ module ].style[ key ];
1239 media = undefined;
1240
1241 if ( key !== 'url' && key !== 'css' ) {
1242 // Backwards compatibility, key is a media-type
1243 if ( typeof value === 'string' ) {
1244 // back-compat: { <media>: css }
1245 // Ignore 'media' because it isn't supported (nor was it used).
1246 // Strings are pre-wrapped in "@media". The media-type was just ""
1247 // (because it had to be set to something).
1248 // This is one of the reasons why this format is no longer used.
1249 addEmbeddedCSS( value, cssHandle() );
1250 } else {
1251 // back-compat: { <media>: [url, ..] }
1252 media = key;
1253 key = 'bc-url';
1254 }
1255 }
1256
1257 // Array of css strings in key 'css',
1258 // or back-compat array of urls from media-type
1259 if ( Array.isArray( value ) ) {
1260 for ( i = 0; i < value.length; i++ ) {
1261 if ( key === 'bc-url' ) {
1262 // back-compat: { <media>: [url, ..] }
1263 addLink( media, value[ i ] );
1264 } else if ( key === 'css' ) {
1265 // { "css": [css, ..] }
1266 addEmbeddedCSS( value[ i ], cssHandle() );
1267 }
1268 }
1269 // Not an array, but a regular object
1270 // Array of urls inside media-type key
1271 } else if ( typeof value === 'object' ) {
1272 // { "url": { <media>: [url, ..] } }
1273 for ( media in value ) {
1274 urls = value[ media ];
1275 for ( i = 0; i < urls.length; i++ ) {
1276 addLink( media, urls[ i ] );
1277 }
1278 }
1279 }
1280 }
1281 }
1282
1283 // Kick off.
1284 cssHandlesRegistered = true;
1285 checkCssHandles();
1286 }
1287
1288 function sortQuery( o ) {
1289 var key,
1290 sorted = {},
1291 a = [];
1292
1293 for ( key in o ) {
1294 a.push( key );
1295 }
1296 a.sort();
1297 for ( key = 0; key < a.length; key++ ) {
1298 sorted[ a[ key ] ] = o[ a[ key ] ];
1299 }
1300 return sorted;
1301 }
1302
1303 /**
1304 * Converts a module map of the form `{ foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }`
1305 * to a query string of the form `foo.bar,baz|bar.baz,quux`.
1306 *
1307 * See `ResourceLoader::makePackedModulesString()` in PHP, of which this is a port.
1308 * On the server, unpacking is done by `ResourceLoaderContext::expandModuleNames()`.
1309 *
1310 * Note: This is only half of the logic, the other half has to be in #batchRequest(),
1311 * because its implementation needs to keep track of potential string size in order
1312 * to decide when to split the requests due to url size.
1313 *
1314 * @private
1315 * @param {Object} moduleMap Module map
1316 * @return {Object}
1317 * @return {string} return.str Module query string
1318 * @return {Array} return.list List of module names in matching order
1319 */
1320 function buildModulesString( moduleMap ) {
1321 var p, prefix,
1322 str = [],
1323 list = [];
1324
1325 function restore( suffix ) {
1326 return p + suffix;
1327 }
1328
1329 for ( prefix in moduleMap ) {
1330 p = prefix === '' ? '' : prefix + '.';
1331 str.push( p + moduleMap[ prefix ].join( ',' ) );
1332 list.push.apply( list, moduleMap[ prefix ].map( restore ) );
1333 }
1334 return {
1335 str: str.join( '|' ),
1336 list: list
1337 };
1338 }
1339
1340 /**
1341 * Resolve indexed dependencies.
1342 *
1343 * ResourceLoader uses an optimization to save space which replaces module names in
1344 * dependency lists with the index of that module within the array of module
1345 * registration data if it exists. The benefit is a significant reduction in the data
1346 * size of the startup module. This function changes those dependency lists back to
1347 * arrays of strings.
1348 *
1349 * @private
1350 * @param {Array} modules Modules array
1351 */
1352 function resolveIndexedDependencies( modules ) {
1353 var i, j, deps;
1354 function resolveIndex( dep ) {
1355 return typeof dep === 'number' ? modules[ dep ][ 0 ] : dep;
1356 }
1357 for ( i = 0; i < modules.length; i++ ) {
1358 deps = modules[ i ][ 2 ];
1359 if ( deps ) {
1360 for ( j = 0; j < deps.length; j++ ) {
1361 deps[ j ] = resolveIndex( deps[ j ] );
1362 }
1363 }
1364 }
1365 }
1366
1367 /**
1368 * @private
1369 * @param {Object} params Map of parameter names to values
1370 * @return {string}
1371 */
1372 function makeQueryString( params ) {
1373 return Object.keys( params ).map( function ( key ) {
1374 return encodeURIComponent( key ) + '=' + encodeURIComponent( params[ key ] );
1375 } ).join( '&' );
1376 }
1377
1378 /**
1379 * Create network requests for a batch of modules.
1380 *
1381 * This is an internal method for #work(). This must not be called directly
1382 * unless the modules are already registered, and no request is in progress,
1383 * and the module state has already been set to `loading`.
1384 *
1385 * @private
1386 * @param {string[]} batch
1387 */
1388 function batchRequest( batch ) {
1389 var reqBase, splits, maxQueryLength, b, bSource, bGroup, bSourceGroup,
1390 source, group, i, modules, sourceLoadScript,
1391 currReqBase, currReqBaseLength, moduleMap, currReqModules, l,
1392 lastDotIndex, prefix, suffix, bytesAdded;
1393
1394 /**
1395 * Start the currently drafted request to the server.
1396 *
1397 * @ignore
1398 */
1399 function doRequest() {
1400 // Optimisation: Inherit (Object.create), not copy ($.extend)
1401 var query = Object.create( currReqBase ),
1402 packed = buildModulesString( moduleMap );
1403 query.modules = packed.str;
1404 // The packing logic can change the effective order, even if the input was
1405 // sorted. As such, the call to getCombinedVersion() must use this
1406 // effective order, instead of currReqModules, as otherwise the combined
1407 // version will not match the hash expected by the server based on
1408 // combining versions from the module query string in-order. (T188076)
1409 query.version = getCombinedVersion( packed.list );
1410 query = sortQuery( query );
1411 addScript( sourceLoadScript + '?' + makeQueryString( query ) );
1412 }
1413
1414 if ( !batch.length ) {
1415 return;
1416 }
1417
1418 // Always order modules alphabetically to help reduce cache
1419 // misses for otherwise identical content.
1420 batch.sort();
1421
1422 // Query parameters common to all requests
1423 reqBase = {
1424 skin: mw.config.get( 'skin' ),
1425 lang: mw.config.get( 'wgUserLanguage' ),
1426 debug: mw.config.get( 'debug' )
1427 };
1428 maxQueryLength = mw.config.get( 'wgResourceLoaderMaxQueryLength', 2000 );
1429
1430 // Split module list by source and by group.
1431 splits = {};
1432 for ( b = 0; b < batch.length; b++ ) {
1433 bSource = registry[ batch[ b ] ].source;
1434 bGroup = registry[ batch[ b ] ].group;
1435 if ( !hasOwn.call( splits, bSource ) ) {
1436 splits[ bSource ] = {};
1437 }
1438 if ( !hasOwn.call( splits[ bSource ], bGroup ) ) {
1439 splits[ bSource ][ bGroup ] = [];
1440 }
1441 bSourceGroup = splits[ bSource ][ bGroup ];
1442 bSourceGroup.push( batch[ b ] );
1443 }
1444
1445 for ( source in splits ) {
1446
1447 sourceLoadScript = sources[ source ];
1448
1449 for ( group in splits[ source ] ) {
1450
1451 // Cache access to currently selected list of
1452 // modules for this group from this source.
1453 modules = splits[ source ][ group ];
1454
1455 // Query parameters common to requests for this module group
1456 // Optimisation: Inherit (Object.create), not copy ($.extend)
1457 currReqBase = Object.create( reqBase );
1458 // User modules require a user name in the query string.
1459 if ( group === 'user' && mw.config.get( 'wgUserName' ) !== null ) {
1460 currReqBase.user = mw.config.get( 'wgUserName' );
1461 }
1462
1463 // In addition to currReqBase, doRequest() will also add 'modules' and 'version'.
1464 // > '&modules='.length === 9
1465 // > '&version=1234567'.length === 16
1466 // > 9 + 16 = 25
1467 currReqBaseLength = makeQueryString( currReqBase ).length + 25;
1468
1469 // We may need to split up the request to honor the query string length limit,
1470 // so build it piece by piece.
1471 l = currReqBaseLength;
1472 moduleMap = {}; // { prefix: [ suffixes ] }
1473 currReqModules = [];
1474
1475 for ( i = 0; i < modules.length; i++ ) {
1476 // Determine how many bytes this module would add to the query string
1477 lastDotIndex = modules[ i ].lastIndexOf( '.' );
1478 // If lastDotIndex is -1, substr() returns an empty string
1479 prefix = modules[ i ].substr( 0, lastDotIndex );
1480 suffix = modules[ i ].slice( lastDotIndex + 1 );
1481 bytesAdded = hasOwn.call( moduleMap, prefix ) ?
1482 suffix.length + 3 : // '%2C'.length == 3
1483 modules[ i ].length + 3; // '%7C'.length == 3
1484
1485 // If the url would become too long, create a new one, but don't create empty requests
1486 if ( maxQueryLength > 0 && currReqModules.length && l + bytesAdded > maxQueryLength ) {
1487 // Dispatch what we've got...
1488 doRequest();
1489 // .. and start again.
1490 l = currReqBaseLength;
1491 moduleMap = {};
1492 currReqModules = [];
1493
1494 mw.track( 'resourceloader.splitRequest', { maxQueryLength: maxQueryLength } );
1495 }
1496 if ( !hasOwn.call( moduleMap, prefix ) ) {
1497 moduleMap[ prefix ] = [];
1498 }
1499 l += bytesAdded;
1500 moduleMap[ prefix ].push( suffix );
1501 currReqModules.push( modules[ i ] );
1502 }
1503 // If there's anything left in moduleMap, request that too
1504 if ( currReqModules.length ) {
1505 doRequest();
1506 }
1507 }
1508 }
1509 }
1510
1511 /**
1512 * @private
1513 * @param {string[]} implementations Array containing pieces of JavaScript code in the
1514 * form of calls to mw.loader#implement().
1515 * @param {Function} cb Callback in case of failure
1516 * @param {Error} cb.err
1517 */
1518 function asyncEval( implementations, cb ) {
1519 if ( !implementations.length ) {
1520 return;
1521 }
1522 mw.requestIdleCallback( function () {
1523 try {
1524 domEval( implementations.join( ';' ) );
1525 } catch ( err ) {
1526 cb( err );
1527 }
1528 } );
1529 }
1530
1531 /**
1532 * Make a versioned key for a specific module.
1533 *
1534 * @private
1535 * @param {string} module Module name
1536 * @return {string|null} Module key in format '`[name]@[version]`',
1537 * or null if the module does not exist
1538 */
1539 function getModuleKey( module ) {
1540 return hasOwn.call( registry, module ) ?
1541 ( module + '@' + registry[ module ].version ) : null;
1542 }
1543
1544 /**
1545 * @private
1546 * @param {string} key Module name or '`[name]@[version]`'
1547 * @return {Object}
1548 */
1549 function splitModuleKey( key ) {
1550 var index = key.indexOf( '@' );
1551 if ( index === -1 ) {
1552 return {
1553 name: key,
1554 version: ''
1555 };
1556 }
1557 return {
1558 name: key.slice( 0, index ),
1559 version: key.slice( index + 1 )
1560 };
1561 }
1562
1563 /* Public Members */
1564 return {
1565 /**
1566 * The module registry is exposed as an aid for debugging and inspecting page
1567 * state; it is not a public interface for modifying the registry.
1568 *
1569 * @see #registry
1570 * @property
1571 * @private
1572 */
1573 moduleRegistry: registry,
1574
1575 /**
1576 * @inheritdoc #newStyleTag
1577 * @method
1578 */
1579 addStyleTag: newStyleTag,
1580
1581 enqueue: enqueue,
1582
1583 resolve: resolve,
1584
1585 /**
1586 * Start loading of all queued module dependencies.
1587 *
1588 * @protected
1589 */
1590 work: function () {
1591 var q, batch, implementations, sourceModules;
1592
1593 batch = [];
1594
1595 // Appends a list of modules from the queue to the batch
1596 for ( q = 0; q < queue.length; q++ ) {
1597 // Only load modules which are registered
1598 if ( hasOwn.call( registry, queue[ q ] ) && registry[ queue[ q ] ].state === 'registered' ) {
1599 // Prevent duplicate entries
1600 if ( batch.indexOf( queue[ q ] ) === -1 ) {
1601 batch.push( queue[ q ] );
1602 // Mark registered modules as loading
1603 registry[ queue[ q ] ].state = 'loading';
1604 }
1605 }
1606 }
1607
1608 // Now that the queue has been processed into a batch, clear the queue.
1609 // This MUST happen before we initiate any eval or network request. Otherwise,
1610 // it is possible for a cached script to instantly trigger the same work queue
1611 // again; all before we've cleared it causing each request to include modules
1612 // which are already loaded.
1613 queue = [];
1614
1615 if ( !batch.length ) {
1616 return;
1617 }
1618
1619 mw.loader.store.init();
1620 if ( mw.loader.store.enabled ) {
1621 implementations = [];
1622 sourceModules = [];
1623 batch = batch.filter( function ( module ) {
1624 var implementation = mw.loader.store.get( module );
1625 if ( implementation ) {
1626 implementations.push( implementation );
1627 sourceModules.push( module );
1628 return false;
1629 }
1630 return true;
1631 } );
1632 asyncEval( implementations, function ( err ) {
1633 var failed;
1634 // Not good, the cached mw.loader.implement calls failed! This should
1635 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1636 // Depending on how corrupt the string is, it is likely that some
1637 // modules' implement() succeeded while the ones after the error will
1638 // never run and leave their modules in the 'loading' state forever.
1639 mw.loader.store.stats.failed++;
1640
1641 // Since this is an error not caused by an individual module but by
1642 // something that infected the implement call itself, don't take any
1643 // risks and clear everything in this cache.
1644 mw.loader.store.clear();
1645
1646 mw.trackError( 'resourceloader.exception', {
1647 exception: err,
1648 source: 'store-eval'
1649 } );
1650 // Re-add the failed ones that are still pending back to the batch
1651 failed = sourceModules.filter( function ( module ) {
1652 return registry[ module ].state === 'loading';
1653 } );
1654 batchRequest( failed );
1655 } );
1656 }
1657
1658 batchRequest( batch );
1659 },
1660
1661 /**
1662 * Register a source.
1663 *
1664 * The #work() method will use this information to split up requests by source.
1665 *
1666 * mw.loader.addSource( 'mediawikiwiki', '//www.mediawiki.org/w/load.php' );
1667 *
1668 * @param {string|Object} id Source ID, or object mapping ids to load urls
1669 * @param {string} loadUrl Url to a load.php end point
1670 * @throws {Error} If source id is already registered
1671 */
1672 addSource: function ( id, loadUrl ) {
1673 var source;
1674 // Allow multiple additions
1675 if ( typeof id === 'object' ) {
1676 for ( source in id ) {
1677 mw.loader.addSource( source, id[ source ] );
1678 }
1679 return;
1680 }
1681
1682 if ( hasOwn.call( sources, id ) ) {
1683 throw new Error( 'source already registered: ' + id );
1684 }
1685
1686 sources[ id ] = loadUrl;
1687 },
1688
1689 /**
1690 * Register a module, letting the system know about it and its properties.
1691 *
1692 * The startup modules contain calls to this method.
1693 *
1694 * When using multiple module registration by passing an array, dependencies that
1695 * are specified as references to modules within the array will be resolved before
1696 * the modules are registered.
1697 *
1698 * @param {string|Array} module Module name or array of arrays, each containing
1699 * a list of arguments compatible with this method
1700 * @param {string|number} version Module version hash (falls backs to empty string)
1701 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1702 * @param {string|Array} dependencies One string or array of strings of module
1703 * names on which this module depends.
1704 * @param {string} [group=null] Group which the module is in
1705 * @param {string} [source='local'] Name of the source
1706 * @param {string} [skip=null] Script body of the skip function
1707 */
1708 register: function ( module, version, dependencies, group, source, skip ) {
1709 var i, deps;
1710 // Allow multiple registration
1711 if ( typeof module === 'object' ) {
1712 resolveIndexedDependencies( module );
1713 for ( i = 0; i < module.length; i++ ) {
1714 // module is an array of module names
1715 if ( typeof module[ i ] === 'string' ) {
1716 mw.loader.register( module[ i ] );
1717 // module is an array of arrays
1718 } else if ( typeof module[ i ] === 'object' ) {
1719 mw.loader.register.apply( mw.loader, module[ i ] );
1720 }
1721 }
1722 return;
1723 }
1724 if ( hasOwn.call( registry, module ) ) {
1725 throw new Error( 'module already registered: ' + module );
1726 }
1727 if ( typeof dependencies === 'string' ) {
1728 // A single module name
1729 deps = [ dependencies ];
1730 } else if ( typeof dependencies === 'object' ) {
1731 // Array of module names
1732 deps = dependencies;
1733 }
1734 // List the module as registered
1735 registry[ module ] = {
1736 // Exposed to execute() for mw.loader.implement() closures.
1737 // Import happens via require().
1738 module: {
1739 exports: {}
1740 },
1741 version: version !== undefined ? String( version ) : '',
1742 dependencies: deps || [],
1743 group: typeof group === 'string' ? group : null,
1744 source: typeof source === 'string' ? source : 'local',
1745 state: 'registered',
1746 skip: typeof skip === 'string' ? skip : null
1747 };
1748 },
1749
1750 /**
1751 * Implement a module given the components that make up the module.
1752 *
1753 * When #load() or #using() requests one or more modules, the server
1754 * response contain calls to this function.
1755 *
1756 * @param {string} module Name of module and current module version. Formatted
1757 * as '`[name]@[version]`". This version should match the requested version
1758 * (from #batchRequest and #registry). This avoids race conditions (T117587).
1759 * For back-compat with MediaWiki 1.27 and earlier, the version may be omitted.
1760 * @param {Function|Array|string} [script] Function with module code, list of URLs
1761 * to load via `<script src>`, or string of module code for `$.globalEval()`.
1762 * @param {Object} [style] Should follow one of the following patterns:
1763 *
1764 * { "css": [css, ..] }
1765 * { "url": { <media>: [url, ..] } }
1766 *
1767 * And for backwards compatibility (needs to be supported forever due to caching):
1768 *
1769 * { <media>: css }
1770 * { <media>: [url, ..] }
1771 *
1772 * The reason css strings are not concatenated anymore is T33676. We now check
1773 * whether it's safe to extend the stylesheet.
1774 *
1775 * @protected
1776 * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1777 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1778 */
1779 implement: function ( module, script, style, messages, templates ) {
1780 var split = splitModuleKey( module ),
1781 name = split.name,
1782 version = split.version;
1783 // Automatically register module
1784 if ( !hasOwn.call( registry, name ) ) {
1785 mw.loader.register( name );
1786 }
1787 // Check for duplicate implementation
1788 if ( hasOwn.call( registry, name ) && registry[ name ].script !== undefined ) {
1789 throw new Error( 'module already implemented: ' + name );
1790 }
1791 if ( version ) {
1792 // Without this reset, if there is a version mismatch between the
1793 // requested and received module version, then mw.loader.store would
1794 // cache the response under the requested key. Thus poisoning the cache
1795 // indefinitely with a stale value. (T117587)
1796 registry[ name ].version = version;
1797 }
1798 // Attach components
1799 registry[ name ].script = script || null;
1800 registry[ name ].style = style || null;
1801 registry[ name ].messages = messages || null;
1802 registry[ name ].templates = templates || null;
1803 // The module may already have been marked as erroneous
1804 if ( registry[ name ].state !== 'error' && registry[ name ].state !== 'missing' ) {
1805 registry[ name ].state = 'loaded';
1806 if ( allReady( registry[ name ].dependencies ) ) {
1807 execute( name );
1808 }
1809 }
1810 },
1811
1812 /**
1813 * Load an external script or one or more modules.
1814 *
1815 * This method takes a list of unrelated modules. Use cases:
1816 *
1817 * - A web page will be composed of many different widgets. These widgets independently
1818 * queue their ResourceLoader modules (`OutputPage::addModules()`). If any of them
1819 * have problems, or are no longer known (e.g. cached HTML), the other modules
1820 * should still be loaded.
1821 * - This method is used for preloading, which must not throw. Later code that
1822 * calls #using() will handle the error.
1823 *
1824 * @param {string|Array} modules Either the name of a module, array of modules,
1825 * or a URL of an external script or style
1826 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
1827 * external script or style; acceptable values are "text/css" and
1828 * "text/javascript"; if no type is provided, text/javascript is assumed.
1829 */
1830 load: function ( modules, type ) {
1831 var filtered, l;
1832
1833 // Allow calling with a url or single dependency as a string
1834 if ( typeof modules === 'string' ) {
1835 // "https://example.org/x.js", "http://example.org/x.js", "//example.org/x.js", "/x.js"
1836 if ( /^(https?:)?\/?\//.test( modules ) ) {
1837 if ( type === 'text/css' ) {
1838 l = document.createElement( 'link' );
1839 l.rel = 'stylesheet';
1840 l.href = modules;
1841 document.head.appendChild( l );
1842 return;
1843 }
1844 if ( type === 'text/javascript' || type === undefined ) {
1845 addScript( modules );
1846 return;
1847 }
1848 // Unknown type
1849 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type );
1850 }
1851 // Called with single module
1852 modules = [ modules ];
1853 }
1854
1855 // Filter out top-level modules that are unknown or failed to load before.
1856 filtered = modules.filter( function ( module ) {
1857 var state = mw.loader.getState( module );
1858 return state !== 'error' && state !== 'missing';
1859 } );
1860 // Resolve remaining list using the known dependency tree.
1861 // This also filters out modules with unknown dependencies. (T36853)
1862 filtered = resolveStubbornly( filtered );
1863 // Some modules are not yet ready, add to module load queue.
1864 enqueue( filtered, undefined, undefined );
1865 },
1866
1867 /**
1868 * Change the state of one or more modules.
1869 *
1870 * @param {string|Object} module Module name or object of module name/state pairs
1871 * @param {string} state State name
1872 */
1873 state: function ( module, state ) {
1874 var m;
1875
1876 if ( typeof module === 'object' ) {
1877 for ( m in module ) {
1878 mw.loader.state( m, module[ m ] );
1879 }
1880 return;
1881 }
1882 if ( !hasOwn.call( registry, module ) ) {
1883 mw.loader.register( module );
1884 }
1885 registry[ module ].state = state;
1886 if ( state === 'ready' || state === 'error' || state === 'missing' ) {
1887 // Make sure pending modules depending on this one get executed if their
1888 // dependencies are now fulfilled!
1889 handlePending( module );
1890 }
1891 },
1892
1893 /**
1894 * Get the version of a module.
1895 *
1896 * @param {string} module Name of module
1897 * @return {string|null} The version, or null if the module (or its version) is not
1898 * in the registry.
1899 */
1900 getVersion: function ( module ) {
1901 return hasOwn.call( registry, module ) ? registry[ module ].version : null;
1902 },
1903
1904 /**
1905 * Get the state of a module.
1906 *
1907 * @param {string} module Name of module
1908 * @return {string|null} The state, or null if the module (or its state) is not
1909 * in the registry.
1910 */
1911 getState: function ( module ) {
1912 return hasOwn.call( registry, module ) ? registry[ module ].state : null;
1913 },
1914
1915 /**
1916 * Get the names of all registered modules.
1917 *
1918 * @return {Array}
1919 */
1920 getModuleNames: function () {
1921 return Object.keys( registry );
1922 },
1923
1924 /**
1925 * Get the exported value of a module.
1926 *
1927 * This static method is publicly exposed for debugging purposes
1928 * only and must not be used in production code. In production code,
1929 * please use the dynamically provided `require()` function instead.
1930 *
1931 * In case of lazy-loaded modules via mw.loader#using(), the returned
1932 * Promise provides the function, see #using() for examples.
1933 *
1934 * @private
1935 * @since 1.27
1936 * @param {string} moduleName Module name
1937 * @return {Mixed} Exported value
1938 */
1939 require: function ( moduleName ) {
1940 var state = mw.loader.getState( moduleName );
1941
1942 // Only ready modules can be required
1943 if ( state !== 'ready' ) {
1944 // Module may've forgotten to declare a dependency
1945 throw new Error( 'Module "' + moduleName + '" is not loaded.' );
1946 }
1947
1948 return registry[ moduleName ].module.exports;
1949 },
1950
1951 /**
1952 * On browsers that implement the localStorage API, the module store serves as a
1953 * smart complement to the browser cache. Unlike the browser cache, the module store
1954 * can slice a concatenated response from ResourceLoader into its constituent
1955 * modules and cache each of them separately, using each module's versioning scheme
1956 * to determine when the cache should be invalidated.
1957 *
1958 * @singleton
1959 * @class mw.loader.store
1960 */
1961 store: {
1962 // Whether the store is in use on this page.
1963 enabled: null,
1964
1965 // Modules whose string representation exceeds 100 kB are
1966 // ineligible for storage. See bug T66721.
1967 MODULE_SIZE_MAX: 100 * 1000,
1968
1969 // The contents of the store, mapping '[name]@[version]' keys
1970 // to module implementations.
1971 items: {},
1972
1973 // Cache hit stats
1974 stats: { hits: 0, misses: 0, expired: 0, failed: 0 },
1975
1976 /**
1977 * Construct a JSON-serializable object representing the content of the store.
1978 *
1979 * @return {Object} Module store contents.
1980 */
1981 toJSON: function () {
1982 return { items: mw.loader.store.items, vary: mw.loader.store.getVary() };
1983 },
1984
1985 /**
1986 * Get the localStorage key for the entire module store. The key references
1987 * $wgDBname to prevent clashes between wikis which share a common host.
1988 *
1989 * @return {string} localStorage item key
1990 */
1991 getStoreKey: function () {
1992 return 'MediaWikiModuleStore:' + mw.config.get( 'wgDBname' );
1993 },
1994
1995 /**
1996 * Get a key on which to vary the module cache.
1997 *
1998 * @return {string} String of concatenated vary conditions.
1999 */
2000 getVary: function () {
2001 return [
2002 mw.config.get( 'skin' ),
2003 mw.config.get( 'wgResourceLoaderStorageVersion' ),
2004 mw.config.get( 'wgUserLanguage' )
2005 ].join( ':' );
2006 },
2007
2008 /**
2009 * Initialize the store.
2010 *
2011 * Retrieves store from localStorage and (if successfully retrieved) decoding
2012 * the stored JSON value to a plain object.
2013 *
2014 * The try / catch block is used for JSON & localStorage feature detection.
2015 * See the in-line documentation for Modernizr's localStorage feature detection
2016 * code for a full account of why we need a try / catch:
2017 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2018 */
2019 init: function () {
2020 var raw, data;
2021
2022 if ( mw.loader.store.enabled !== null ) {
2023 // Init already ran
2024 return;
2025 }
2026
2027 if (
2028 // Disabled because localStorage quotas are tight and (in Firefox's case)
2029 // shared by multiple origins.
2030 // See T66721, and <https://bugzilla.mozilla.org/show_bug.cgi?id=1064466>.
2031 /Firefox|Opera/.test( navigator.userAgent ) ||
2032
2033 // Disabled by configuration.
2034 !mw.config.get( 'wgResourceLoaderStorageEnabled' )
2035 ) {
2036 // Clear any previous store to free up space. (T66721)
2037 mw.loader.store.clear();
2038 mw.loader.store.enabled = false;
2039 return;
2040 }
2041 if ( mw.config.get( 'debug' ) ) {
2042 // Disable module store in debug mode
2043 mw.loader.store.enabled = false;
2044 return;
2045 }
2046
2047 try {
2048 raw = localStorage.getItem( mw.loader.store.getStoreKey() );
2049 // If we get here, localStorage is available; mark enabled
2050 mw.loader.store.enabled = true;
2051 data = JSON.parse( raw );
2052 if ( data && typeof data.items === 'object' && data.vary === mw.loader.store.getVary() ) {
2053 mw.loader.store.items = data.items;
2054 return;
2055 }
2056 } catch ( e ) {
2057 mw.trackError( 'resourceloader.exception', {
2058 exception: e,
2059 source: 'store-localstorage-init'
2060 } );
2061 }
2062
2063 if ( raw === undefined ) {
2064 // localStorage failed; disable store
2065 mw.loader.store.enabled = false;
2066 } else {
2067 mw.loader.store.update();
2068 }
2069 },
2070
2071 /**
2072 * Retrieve a module from the store and update cache hit stats.
2073 *
2074 * @param {string} module Module name
2075 * @return {string|boolean} Module implementation or false if unavailable
2076 */
2077 get: function ( module ) {
2078 var key;
2079
2080 if ( !mw.loader.store.enabled ) {
2081 return false;
2082 }
2083
2084 key = getModuleKey( module );
2085 if ( key in mw.loader.store.items ) {
2086 mw.loader.store.stats.hits++;
2087 return mw.loader.store.items[ key ];
2088 }
2089 mw.loader.store.stats.misses++;
2090 return false;
2091 },
2092
2093 /**
2094 * Stringify a module and queue it for storage.
2095 *
2096 * @param {string} module Module name
2097 * @param {Object} descriptor The module's descriptor as set in the registry
2098 * @return {boolean} Module was set
2099 */
2100 set: function ( module, descriptor ) {
2101 var args, key, src;
2102
2103 if ( !mw.loader.store.enabled ) {
2104 return false;
2105 }
2106
2107 key = getModuleKey( module );
2108
2109 if (
2110 // Already stored a copy of this exact version
2111 key in mw.loader.store.items ||
2112 // Module failed to load
2113 descriptor.state !== 'ready' ||
2114 // Unversioned, private, or site-/user-specific
2115 !descriptor.version ||
2116 descriptor.group === 'private' ||
2117 descriptor.group === 'user' ||
2118 // Partial descriptor
2119 // (e.g. skipped module, or style module with state=ready)
2120 [ descriptor.script, descriptor.style, descriptor.messages,
2121 descriptor.templates ].indexOf( undefined ) !== -1
2122 ) {
2123 // Decline to store
2124 return false;
2125 }
2126
2127 try {
2128 args = [
2129 JSON.stringify( key ),
2130 typeof descriptor.script === 'function' ?
2131 String( descriptor.script ) :
2132 JSON.stringify( descriptor.script ),
2133 JSON.stringify( descriptor.style ),
2134 JSON.stringify( descriptor.messages ),
2135 JSON.stringify( descriptor.templates )
2136 ];
2137 // Attempted workaround for a possible Opera bug (bug T59567).
2138 // This regex should never match under sane conditions.
2139 if ( /^\s*\(/.test( args[ 1 ] ) ) {
2140 args[ 1 ] = 'function' + args[ 1 ];
2141 mw.trackError( 'resourceloader.assert', { source: 'bug-T59567' } );
2142 }
2143 } catch ( e ) {
2144 mw.trackError( 'resourceloader.exception', {
2145 exception: e,
2146 source: 'store-localstorage-json'
2147 } );
2148 return false;
2149 }
2150
2151 src = 'mw.loader.implement(' + args.join( ',' ) + ');';
2152 if ( src.length > mw.loader.store.MODULE_SIZE_MAX ) {
2153 return false;
2154 }
2155 mw.loader.store.items[ key ] = src;
2156 mw.loader.store.update();
2157 return true;
2158 },
2159
2160 /**
2161 * Iterate through the module store, removing any item that does not correspond
2162 * (in name and version) to an item in the module registry.
2163 *
2164 * @return {boolean} Store was pruned
2165 */
2166 prune: function () {
2167 var key, module;
2168
2169 if ( !mw.loader.store.enabled ) {
2170 return false;
2171 }
2172
2173 for ( key in mw.loader.store.items ) {
2174 module = key.slice( 0, key.indexOf( '@' ) );
2175 if ( getModuleKey( module ) !== key ) {
2176 mw.loader.store.stats.expired++;
2177 delete mw.loader.store.items[ key ];
2178 } else if ( mw.loader.store.items[ key ].length > mw.loader.store.MODULE_SIZE_MAX ) {
2179 // This value predates the enforcement of a size limit on cached modules.
2180 delete mw.loader.store.items[ key ];
2181 }
2182 }
2183 return true;
2184 },
2185
2186 /**
2187 * Clear the entire module store right now.
2188 */
2189 clear: function () {
2190 mw.loader.store.items = {};
2191 try {
2192 localStorage.removeItem( mw.loader.store.getStoreKey() );
2193 } catch ( ignored ) {}
2194 },
2195
2196 /**
2197 * Sync in-memory store back to localStorage.
2198 *
2199 * This function debounces updates. When called with a flush already pending,
2200 * the call is coalesced into the pending update. The call to
2201 * localStorage.setItem will be naturally deferred until the page is quiescent.
2202 *
2203 * Because localStorage is shared by all pages from the same origin, if multiple
2204 * pages are loaded with different module sets, the possibility exists that
2205 * modules saved by one page will be clobbered by another. But the impact would
2206 * be minor and the problem would be corrected by subsequent page views.
2207 *
2208 * @method
2209 */
2210 update: ( function () {
2211 var hasPendingWrite = false;
2212
2213 function flushWrites() {
2214 var data, key;
2215 if ( !hasPendingWrite || !mw.loader.store.enabled ) {
2216 return;
2217 }
2218
2219 mw.loader.store.prune();
2220 key = mw.loader.store.getStoreKey();
2221 try {
2222 // Replacing the content of the module store might fail if the new
2223 // contents would exceed the browser's localStorage size limit. To
2224 // avoid clogging the browser with stale data, always remove the old
2225 // value before attempting to set the new one.
2226 localStorage.removeItem( key );
2227 data = JSON.stringify( mw.loader.store );
2228 localStorage.setItem( key, data );
2229 } catch ( e ) {
2230 mw.trackError( 'resourceloader.exception', {
2231 exception: e,
2232 source: 'store-localstorage-update'
2233 } );
2234 }
2235
2236 hasPendingWrite = false;
2237 }
2238
2239 return function () {
2240 if ( !hasPendingWrite ) {
2241 hasPendingWrite = true;
2242 mw.requestIdleCallback( flushWrites );
2243 }
2244 };
2245 }() )
2246 }
2247 };
2248 }() ),
2249
2250 // Skeleton user object, extended by the 'mediawiki.user' module.
2251 /**
2252 * @class mw.user
2253 * @singleton
2254 */
2255 user: {
2256 /**
2257 * @property {mw.Map}
2258 */
2259 options: new Map(),
2260 /**
2261 * @property {mw.Map}
2262 */
2263 tokens: new Map()
2264 },
2265
2266 // OOUI widgets specific to MediaWiki
2267 widgets: {}
2268
2269 };
2270
2271 // Attach to window and globally alias
2272 window.mw = window.mediaWiki = mw;
2273 }() );