2 * Base library for MediaWiki.
4 * Exposed globally as `mediaWiki` with `mw` as shortcut.
7 * @alternateClassName mediaWiki
12 /* eslint-disable no-use-before-define */
17 var mw
, StringSet
, log
,
18 hasOwn
= Object
.prototype.hasOwnProperty
,
19 slice
= Array
.prototype.slice
,
20 trackCallbacks
= $.Callbacks( 'memory' ),
25 * FNV132 hash function
27 * This function implements the 32-bit version of FNV-1.
28 * It is equivalent to hash( 'fnv132', ... ) in PHP, except
29 * its output is base 36 rather than hex.
30 * See <https://en.wikipedia.org/wiki/FNV_hash_function>
33 * @param {string} str String to hash
34 * @return {string} hash as an seven-character base 36 string
36 function fnv132( str
) {
37 /* eslint-disable no-bitwise */
38 var hash
= 0x811C9DC5,
41 for ( i
= 0; i
< str
.length
; i
++ ) {
42 hash
+= ( hash
<< 1 ) + ( hash
<< 4 ) + ( hash
<< 7 ) + ( hash
<< 8 ) + ( hash
<< 24 );
43 hash
^= str
.charCodeAt( i
);
46 hash
= ( hash
>>> 0 ).toString( 36 );
47 while ( hash
.length
< 7 ) {
52 /* eslint-enable no-bitwise */
55 function defineFallbacks() {
56 // <https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Set>
57 StringSet
= window
.Set
|| ( function () {
62 function StringSet() {
65 StringSet
.prototype.add = function ( value
) {
66 this.set[ value
] = true;
68 StringSet
.prototype.has = function ( value
) {
69 return hasOwn
.call( this.set, value
);
76 * Create an object that can be read from or written to via methods that allow
77 * interaction both with single and multiple properties at once.
83 * @param {boolean} [global=false] Whether to synchronise =values to the global
84 * window object (for backwards-compatibility with mw.config; T72470). Values are
85 * copied in one direction only. Changes to globals do not reflect in the map.
87 function Map( global
) {
89 if ( global
=== true ) {
90 // Override #set to also set the global variable
91 this.set = function ( selection
, value
) {
94 if ( $.isPlainObject( selection
) ) {
95 for ( s
in selection
) {
96 setGlobalMapValue( this, s
, selection
[ s
] );
100 if ( typeof selection
=== 'string' && arguments
.length
) {
101 setGlobalMapValue( this, selection
, value
);
110 * Alias property to the global object.
114 * @param {mw.Map} map
115 * @param {string} key
116 * @param {Mixed} value
118 function setGlobalMapValue( map
, key
, value
) {
119 map
.values
[ key
] = value
;
124 // Deprecation notice for mw.config globals (T58550, T72470)
125 map
=== mw
.config
&& 'Use mw.config instead.'
133 * Get the value of one or more keys.
135 * If called with no arguments, all values are returned.
137 * @param {string|Array} [selection] Key or array of keys to retrieve values for.
138 * @param {Mixed} [fallback=null] Value for keys that don't exist.
139 * @return {Mixed|Object|null} If selection was a string, returns the value,
140 * If selection was an array, returns an object of key/values.
141 * If no selection is passed, a new object with all key/values is returned.
143 get: function ( selection
, fallback
) {
145 fallback
= arguments
.length
> 1 ? fallback
: null;
147 if ( Array
.isArray( selection
) ) {
149 for ( i
= 0; i
< selection
.length
; i
++ ) {
150 if ( typeof selection
[ i
] === 'string' ) {
151 results
[ selection
[ i
] ] = hasOwn
.call( this.values
, selection
[ i
] ) ?
152 this.values
[ selection
[ i
] ] :
159 if ( typeof selection
=== 'string' ) {
160 return hasOwn
.call( this.values
, selection
) ?
161 this.values
[ selection
] :
165 if ( selection
=== undefined ) {
167 for ( i
in this.values
) {
168 results
[ i
] = this.values
[ i
];
173 // Invalid selection key
178 * Set one or more key/value pairs.
180 * @param {string|Object} selection Key to set value for, or object mapping keys to values
181 * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
182 * @return {boolean} True on success, false on failure
184 set: function ( selection
, value
) {
187 if ( $.isPlainObject( selection
) ) {
188 for ( s
in selection
) {
189 this.values
[ s
] = selection
[ s
];
193 if ( typeof selection
=== 'string' && arguments
.length
> 1 ) {
194 this.values
[ selection
] = value
;
201 * Check if one or more keys exist.
203 * @param {Mixed} selection Key or array of keys to check
204 * @return {boolean} True if the key(s) exist
206 exists: function ( selection
) {
208 if ( Array
.isArray( selection
) ) {
209 for ( i
= 0; i
< selection
.length
; i
++ ) {
210 if ( typeof selection
[ i
] !== 'string' || !hasOwn
.call( this.values
, selection
[ i
] ) ) {
216 return typeof selection
=== 'string' && hasOwn
.call( this.values
, selection
);
221 * Object constructor for messages.
223 * Similar to the Message class in MediaWiki PHP.
225 * Format defaults to 'text'.
231 * 'hello': 'Hello world',
232 * 'hello-user': 'Hello, $1!',
233 * 'welcome-user': 'Welcome back to $2, $1! Last visit by $1: $3'
236 * obj = new mw.Message( mw.messages, 'hello' );
237 * mw.log( obj.text() );
240 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John Doe' ] );
241 * mw.log( obj.text() );
242 * // Hello, John Doe!
244 * obj = new mw.Message( mw.messages, 'welcome-user', [ 'John Doe', 'Wikipedia', '2 hours ago' ] );
245 * mw.log( obj.text() );
246 * // Welcome back to Wikipedia, John Doe! Last visit by John Doe: 2 hours ago
248 * // Using mw.message shortcut
249 * obj = mw.message( 'hello-user', 'John Doe' );
250 * mw.log( obj.text() );
251 * // Hello, John Doe!
253 * // Using mw.msg shortcut
254 * str = mw.msg( 'hello-user', 'John Doe' );
256 * // Hello, John Doe!
258 * // Different formats
259 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John "Wiki" <3 Doe' ] );
261 * obj.format = 'text';
262 * str = obj.toString();
267 * // Hello, John "Wiki" <3 Doe!
269 * mw.log( obj.escaped() );
270 * // Hello, John "Wiki" <3 Doe!
275 * @param {mw.Map} map Message store
276 * @param {string} key
277 * @param {Array} [parameters]
279 function Message( map
, key
, parameters
) {
280 this.format
= 'text';
283 this.parameters
= parameters
=== undefined ? [] : slice
.call( parameters
);
287 Message
.prototype = {
289 * Get parsed contents of the message.
291 * The default parser does simple $N replacements and nothing else.
292 * This may be overridden to provide a more complex message parser.
293 * The primary override is in the mediawiki.jqueryMsg module.
295 * This function will not be called for nonexistent messages.
297 * @return {string} Parsed message
299 parser: function () {
300 return mw
.format
.apply( null, [ this.map
.get( this.key
) ].concat( this.parameters
) );
303 // eslint-disable-next-line valid-jsdoc
305 * Add (does not replace) parameters for `$N` placeholder values.
307 * @param {Array} parameters
310 params: function ( parameters
) {
312 for ( i
= 0; i
< parameters
.length
; i
++ ) {
313 this.parameters
.push( parameters
[ i
] );
319 * Convert message object to its string form based on current format.
321 * @return {string} Message as a string in the current form, or `<key>` if key
324 toString: function () {
327 if ( !this.exists() ) {
328 // Use ⧼key⧽ as text if key does not exist
329 // Err on the side of safety, ensure that the output
330 // is always html safe in the event the message key is
331 // missing, since in that case its highly likely the
332 // message key is user-controlled.
333 // '⧼' is used instead of '<' to side-step any
334 // double-escaping issues.
335 // (Keep synchronised with Message::toString() in PHP.)
336 return '⧼' + mw
.html
.escape( this.key
) + '⧽';
339 if ( this.format
=== 'plain' || this.format
=== 'text' || this.format
=== 'parse' ) {
340 text
= this.parser();
343 if ( this.format
=== 'escaped' ) {
344 text
= this.parser();
345 text
= mw
.html
.escape( text
);
352 * Change format to 'parse' and convert message to string
354 * If jqueryMsg is loaded, this parses the message text from wikitext
355 * (where supported) to HTML
357 * Otherwise, it is equivalent to plain.
359 * @return {string} String form of parsed message
362 this.format
= 'parse';
363 return this.toString();
367 * Change format to 'plain' and convert message to string
369 * This substitutes parameters, but otherwise does not change the
372 * @return {string} String form of plain message
375 this.format
= 'plain';
376 return this.toString();
380 * Change format to 'text' and convert message to string
382 * If jqueryMsg is loaded, {{-transformation is done where supported
383 * (such as {{plural:}}, {{gender:}}, {{int:}}).
385 * Otherwise, it is equivalent to plain
387 * @return {string} String form of text message
390 this.format
= 'text';
391 return this.toString();
395 * Change the format to 'escaped' and convert message to string
397 * This is equivalent to using the 'text' format (see #text), then
398 * HTML-escaping the output.
400 * @return {string} String form of html escaped message
402 escaped: function () {
403 this.format
= 'escaped';
404 return this.toString();
408 * Check if a message exists
413 exists: function () {
414 return this.map
.exists( this.key
);
420 /* eslint-disable no-console */
421 log
= ( function () {
423 * Write a verbose message to the browser's console in debug mode.
425 * This method is mainly intended for verbose logging. It is a no-op in production mode.
426 * In ResourceLoader debug mode, it will use the browser's console if available, with
427 * fallback to creating a console interface in the DOM and logging messages there.
429 * See {@link mw.log} for other logging methods.
432 * @param {...string} msg Messages to output to console.
434 var log = function () {},
435 console
= window
.console
;
437 // Note: Keep list of methods in sync with restoration in mediawiki.log.js
438 // when adding or removing mw.log methods below!
441 * Collection of methods to help log messages to the console.
448 * Write a message to the browser console's warning channel.
450 * This method is a no-op in browsers that don't implement the Console API.
452 * @param {...string} msg Messages to output to console
454 log
.warn
= console
&& console
.warn
&& Function
.prototype.bind
?
455 Function
.prototype.bind
.call( console
.warn
, console
) :
459 * Write a message to the browser console's error channel.
461 * Most browsers also print a stacktrace when calling this method if the
462 * argument is an Error object.
464 * This method is a no-op in browsers that don't implement the Console API.
467 * @param {Error|...string} msg Messages to output to console
469 log
.error
= console
&& console
.error
&& Function
.prototype.bind
?
470 Function
.prototype.bind
.call( console
.error
, console
) :
474 * Create a property on a host object that, when accessed, will produce
475 * a deprecation warning in the console.
477 * @param {Object} obj Host object of deprecated property
478 * @param {string} key Name of property to create in `obj`
479 * @param {Mixed} val The value this property should return when accessed
480 * @param {string} [msg] Optional text to include in the deprecation message
481 * @param {string} [logName=key] Optional custom name for the feature.
482 * This is used instead of `key` in the message and `mw.deprecate` tracking.
484 log
.deprecate
= !Object
.defineProperty
? function ( obj
, key
, val
) {
486 } : function ( obj
, key
, val
, msg
, logName
) {
487 var logged
= new StringSet();
488 logName
= logName
|| key
;
489 msg
= 'Use of "' + logName
+ '" is deprecated.' + ( msg
? ( ' ' + msg
) : '' );
490 function uniqueTrace() {
491 var trace
= new Error().stack
;
492 if ( logged
.has( trace
) ) {
498 // Support: Safari 5.0
499 // Throws "not supported on DOM Objects" for Node or Element objects (incl. document)
500 // Safari 4.0 doesn't have this method, and it was fixed in Safari 5.1.
502 Object
.defineProperty( obj
, key
, {
506 if ( uniqueTrace() ) {
507 mw
.track( 'mw.deprecate', logName
);
512 set: function ( newVal
) {
513 if ( uniqueTrace() ) {
514 mw
.track( 'mw.deprecate', logName
);
527 /* eslint-enable no-console */
533 redefineFallbacksForTest: function () {
534 if ( !window
.QUnit
) {
535 throw new Error( 'Reset not allowed outside unit tests' );
541 * Get the current time, measured in milliseconds since January 1, 1970 (UTC).
543 * On browsers that implement the Navigation Timing API, this function will produce floating-point
544 * values with microsecond precision that are guaranteed to be monotonic. On all other browsers,
545 * it will fall back to using `Date`.
547 * @return {number} Current time
550 // mwNow is defined in startup.js
553 * Format a string. Replace $1, $2 ... $N with positional arguments.
555 * Used by Message#parser().
558 * @param {string} formatString Format string
559 * @param {...Mixed} parameters Values for $N replacements
560 * @return {string} Formatted string
562 format: function ( formatString
) {
563 var parameters
= slice
.call( arguments
, 1 );
564 return formatString
.replace( /\$(\d+)/g, function ( str
, match
) {
565 var index
= parseInt( match
, 10 ) - 1;
566 return parameters
[ index
] !== undefined ? parameters
[ index
] : '$' + match
;
571 * Track an analytic event.
573 * This method provides a generic means for MediaWiki JavaScript code to capture state
574 * information for analysis. Each logged event specifies a string topic name that describes
575 * the kind of event that it is. Topic names consist of dot-separated path components,
576 * arranged from most general to most specific. Each path component should have a clear and
577 * well-defined purpose.
579 * Data handlers are registered via `mw.trackSubscribe`, and receive the full set of
580 * events that match their subcription, including those that fired before the handler was
583 * @param {string} topic Topic name
584 * @param {Object} [data] Data describing the event, encoded as an object
586 track: function ( topic
, data
) {
587 trackQueue
.push( { topic
: topic
, timeStamp
: mw
.now(), data
: data
} );
588 trackCallbacks
.fire( trackQueue
);
592 * Register a handler for subset of analytic events, specified by topic.
594 * Handlers will be called once for each tracked event, including any events that fired before the
595 * handler was registered; 'this' is set to a plain object with a 'timeStamp' property indicating
596 * the exact time at which the event fired, a string 'topic' property naming the event, and a
597 * 'data' property which is an object of event-specific data. The event topic and event data are
598 * also passed to the callback as the first and second arguments, respectively.
600 * @param {string} topic Handle events whose name starts with this string prefix
601 * @param {Function} callback Handler to call for each matching tracked event
602 * @param {string} callback.topic
603 * @param {Object} [callback.data]
605 trackSubscribe: function ( topic
, callback
) {
607 function handler( trackQueue
) {
609 for ( ; seen
< trackQueue
.length
; seen
++ ) {
610 event
= trackQueue
[ seen
];
611 if ( event
.topic
.indexOf( topic
) === 0 ) {
612 callback
.call( event
, event
.topic
, event
.data
);
617 trackHandlers
.push( [ handler
, callback
] );
619 trackCallbacks
.add( handler
);
623 * Stop handling events for a particular handler
625 * @param {Function} callback
627 trackUnsubscribe: function ( callback
) {
628 trackHandlers
= $.grep( trackHandlers
, function ( fns
) {
629 if ( fns
[ 1 ] === callback
) {
630 trackCallbacks
.remove( fns
[ 0 ] );
631 // Ensure the tuple is removed to avoid holding on to closures
638 // Expose Map constructor
641 // Expose Message constructor
645 * Map of configuration values.
647 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
650 * If `$wgLegacyJavaScriptGlobals` is true, this Map will add its values to the
651 * global `window` object.
653 * @property {mw.Map} config
655 // Dummy placeholder later assigned in ResourceLoaderStartUpModule
659 * Empty object for third-party libraries, for cases where you don't
660 * want to add a new global, or the global is bad and needs containment
668 * Access container for deprecated functionality that can be moved from
669 * from their legacy location and attached to this object (e.g. a global
670 * function that is deprecated and as stop-gap can be exposed through here).
672 * This was reserved for future use but never ended up being used.
674 * @deprecated since 1.22 Let deprecated identifiers keep their original name
675 * and use mw.log#deprecate to create an access container for tracking.
681 * Store for messages.
688 * Store for templates associated with a module.
692 templates
: new Map(),
695 * Get a message object.
697 * Shortcut for `new mw.Message( mw.messages, key, parameters )`.
700 * @param {string} key Key of message to get
701 * @param {...Mixed} parameters Values for $N replacements
702 * @return {mw.Message}
704 message: function ( key
) {
705 var parameters
= slice
.call( arguments
, 1 );
706 return new Message( mw
.messages
, key
, parameters
);
710 * Get a message string using the (default) 'text' format.
712 * Shortcut for `mw.message( key, parameters... ).text()`.
715 * @param {string} key Key of message to get
716 * @param {...Mixed} parameters Values for $N replacements
720 return mw
.message
.apply( mw
.message
, arguments
).toString();
727 * Client for ResourceLoader server end point.
729 * This client is in charge of maintaining the module registry and state
730 * machine, initiating network (batch) requests for loading modules, as
731 * well as dependency resolution and execution of source code.
733 * For more information, refer to
734 * <https://www.mediawiki.org/wiki/ResourceLoader/Features>
739 loader
: ( function () {
742 * Fired via mw.track on various resource loading errors.
744 * @event resourceloader_exception
745 * @param {Error|Mixed} e The error that was thrown. Almost always an Error
746 * object, but in theory module code could manually throw something else, and that
747 * might also end up here.
748 * @param {string} [module] Name of the module which caused the error. Omitted if the
749 * error is not module-related or the module cannot be easily identified due to
751 * @param {string} source Source of the error. Possible values:
753 * - style: stylesheet error (only affects old IE where a special style loading method
755 * - load-callback: exception thrown by user callback
756 * - module-execute: exception thrown by module code
757 * - store-eval: could not evaluate module code cached in localStorage
758 * - store-localstorage-init: localStorage or JSON parse error in mw.loader.store.init
759 * - store-localstorage-json: JSON conversion error in mw.loader.store.set
760 * - store-localstorage-update: localStorage or JSON conversion error in mw.loader.store.update
764 * Fired via mw.track on resource loading error conditions.
766 * @event resourceloader_assert
767 * @param {string} source Source of the error. Possible values:
769 * - bug-T59567: failed to cache script due to an Opera function -> string conversion
770 * bug; see <https://phabricator.wikimedia.org/T59567> for details
774 * Mapping of registered modules.
776 * See #implement and #execute for exact details on support for script, style and messages.
782 * // From mw.loader.register()
783 * 'version': '########' (hash)
784 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function () {}
785 * 'group': 'somegroup', (or) null
786 * 'source': 'local', (or) 'anotherwiki'
787 * 'skip': 'return !!window.Example', (or) null
788 * 'module': export Object
790 * // Set from execute() or mw.loader.state()
791 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error', or 'missing'
793 * // Optionally added at run-time by mw.loader.implement()
795 * 'script': closure, array of urls, or string
796 * 'style': { ... } (see #execute)
797 * 'messages': { 'key': 'value', ... }
804 * The module is known to the system but not yet required.
805 * Meta data is registered via mw.loader#register. Calls to that method are
806 * generated server-side by the startup module.
808 * The module was required through mw.loader (either directly or as dependency of
809 * another module). The client will fetch module contents from the server.
810 * The contents are then stashed in the registry via mw.loader#implement.
812 * The module has been loaded from the server and stashed via mw.loader#implement.
813 * If the module has no more dependencies in-flight, the module will be executed
814 * immediately. Otherwise execution is deferred, controlled via #handlePending.
816 * The module is being executed.
818 * The module has been successfully executed.
820 * The module (or one of its dependencies) produced an error during execution.
822 * The module was registered client-side and requested, but the server denied knowledge
823 * of the module's existence.
829 // Mapping of sources, keyed by source-id, values are strings.
834 // 'sourceId': 'http://example.org/w/load.php'
839 // For queueModuleScript()
840 handlingPendingRequests
= false,
841 pendingRequests
= [],
843 // List of modules to be loaded
847 * List of callback jobs waiting for modules to be ready.
849 * Jobs are created by #enqueue() and run by #handlePending().
851 * Typically when a job is created for a module, the job's dependencies contain
852 * both the required module and all its recursive dependencies.
857 * 'dependencies': [ module names ],
858 * 'ready': Function callback
859 * 'error': Function callback
862 * @property {Object[]} jobs
870 // For addEmbeddedCSS()
872 cssBufferTimer
= null,
873 cssCallbacks
= $.Callbacks(),
874 rAF
= window
.requestAnimationFrame
|| setTimeout
;
876 function getMarker() {
879 marker
= document
.querySelector( 'meta[name="ResourceLoaderDynamicStyles"]' );
881 mw
.log( 'Create <meta name="ResourceLoaderDynamicStyles"> dynamically' );
882 marker
= $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' )[ 0 ];
889 * Create a new style element and add it to the DOM.
892 * @param {string} text CSS text
893 * @param {Node} [nextNode] The element where the style tag
894 * should be inserted before
895 * @return {HTMLElement} Reference to the created style element
897 function newStyleTag( text
, nextNode
) {
898 var s
= document
.createElement( 'style' );
900 s
.appendChild( document
.createTextNode( text
) );
901 if ( nextNode
&& nextNode
.parentNode
) {
902 nextNode
.parentNode
.insertBefore( s
, nextNode
);
904 document
.getElementsByTagName( 'head' )[ 0 ].appendChild( s
);
911 * Add a bit of CSS text to the current browser page.
913 * The CSS will be appended to an existing ResourceLoader-created `<style>` tag
914 * or create a new one based on whether the given `cssText` is safe for extension.
917 * @param {string} [cssText=cssBuffer] If called without cssText,
918 * the internal buffer will be inserted instead.
919 * @param {Function} [callback]
921 function addEmbeddedCSS( cssText
, callback
) {
922 function fireCallbacks() {
923 var oldCallbacks
= cssCallbacks
;
924 // Reset cssCallbacks variable so it's not polluted by any calls to
925 // addEmbeddedCSS() from one of the callbacks (T105973)
926 cssCallbacks
= $.Callbacks();
927 oldCallbacks
.fire().empty();
931 cssCallbacks
.add( callback
);
934 // Yield once before creating the <style> tag. This lets multiple stylesheets
935 // accumulate into one buffer, allowing us to reduce how often new stylesheets
936 // are inserted in the browser. Appending a stylesheet and waiting for the
937 // browser to repaint is fairly expensive. (T47810)
939 // Don't extend the buffer if the item needs its own stylesheet.
940 // Keywords like `@import` are only valid at the start of a stylesheet (T37562).
941 if ( !cssBuffer
|| cssText
.slice( 0, '@import'.length
) !== '@import' ) {
942 // Linebreak for somewhat distinguishable sections
943 cssBuffer
+= '\n' + cssText
;
944 if ( !cssBufferTimer
) {
945 cssBufferTimer
= rAF( function () {
946 // Wrap in anonymous function that takes no arguments
947 // Support: Firefox < 13
948 // Firefox 12 has non-standard behaviour of passing a number
949 // as first argument to a setTimeout callback.
950 // http://benalman.com/news/2009/07/the-mysterious-firefox-settime/
957 // This is a scheduled flush for the buffer
959 cssBufferTimer
= null;
964 $( newStyleTag( cssText
, getMarker() ) );
971 * @param {Array} modules List of module names
972 * @return {string} Hash of concatenated version hashes.
974 function getCombinedVersion( modules
) {
975 var hashes
= modules
.map( function ( module
) {
976 return registry
[ module
].version
;
978 return fnv132( hashes
.join( '' ) );
982 * Determine whether all dependencies are in state 'ready', which means we may
983 * execute the module or job now.
986 * @param {Array} modules Names of modules to be checked
987 * @return {boolean} True if all modules are in state 'ready', false otherwise
989 function allReady( modules
) {
991 for ( i
= 0; i
< modules
.length
; i
++ ) {
992 if ( mw
.loader
.getState( modules
[ i
] ) !== 'ready' ) {
1000 * Determine whether all dependencies are in state 'ready', which means we may
1001 * execute the module or job now.
1004 * @param {Array} modules Names of modules to be checked
1005 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
1007 function anyFailed( modules
) {
1009 for ( i
= 0; i
< modules
.length
; i
++ ) {
1010 state
= mw
.loader
.getState( modules
[ i
] );
1011 if ( state
=== 'error' || state
=== 'missing' ) {
1019 * A module has entered state 'ready', 'error', or 'missing'. Automatically update
1020 * pending jobs and modules that depend upon this module. If the given module failed,
1021 * propagate the 'error' state up the dependency tree. Otherwise, go ahead and execute
1022 * all jobs/modules now having their dependencies satisfied.
1024 * Jobs that depend on a failed module, will have their error callback ran (if any).
1027 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
1029 function handlePending( module
) {
1030 var j
, job
, hasErrors
, m
, stateChange
;
1032 if ( registry
[ module
].state
=== 'error' || registry
[ module
].state
=== 'missing' ) {
1033 // If the current module failed, mark all dependent modules also as failed.
1034 // Iterate until steady-state to propagate the error state upwards in the
1037 stateChange
= false;
1038 for ( m
in registry
) {
1039 if ( registry
[ m
].state
!== 'error' && registry
[ m
].state
!== 'missing' ) {
1040 if ( anyFailed( registry
[ m
].dependencies
) ) {
1041 registry
[ m
].state
= 'error';
1046 } while ( stateChange
);
1049 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
1050 for ( j
= 0; j
< jobs
.length
; j
++ ) {
1051 hasErrors
= anyFailed( jobs
[ j
].dependencies
);
1052 if ( hasErrors
|| allReady( jobs
[ j
].dependencies
) ) {
1053 // All dependencies satisfied, or some have errors
1055 jobs
.splice( j
, 1 );
1059 if ( typeof job
.error
=== 'function' ) {
1060 job
.error( new Error( 'Module ' + module
+ ' has failed dependencies' ), [ module
] );
1063 if ( typeof job
.ready
=== 'function' ) {
1068 // A user-defined callback raised an exception.
1069 // Swallow it to protect our state machine!
1070 mw
.track( 'resourceloader.exception', { exception
: e
, module
: module
, source
: 'load-callback' } );
1075 if ( registry
[ module
].state
=== 'ready' ) {
1076 // The current module became 'ready'. Set it in the module store, and recursively execute all
1077 // dependent modules that are loaded and now have all dependencies satisfied.
1078 mw
.loader
.store
.set( module
, registry
[ module
] );
1079 for ( m
in registry
) {
1080 if ( registry
[ m
].state
=== 'loaded' && allReady( registry
[ m
].dependencies
) ) {
1088 * Resolve dependencies and detect circular references.
1091 * @param {string} module Name of the top-level module whose dependencies shall be
1092 * resolved and sorted.
1093 * @param {Array} resolved Returns a topological sort of the given module and its
1094 * dependencies, such that later modules depend on earlier modules. The array
1095 * contains the module names. If the array contains already some module names,
1096 * this function appends its result to the pre-existing array.
1097 * @param {StringSet} [unresolved] Used to track the current dependency
1098 * chain, and to report loops in the dependency graph.
1099 * @throws {Error} If any unregistered module or a dependency loop is encountered
1101 function sortDependencies( module
, resolved
, unresolved
) {
1104 if ( !hasOwn
.call( registry
, module
) ) {
1105 throw new Error( 'Unknown dependency: ' + module
);
1108 if ( registry
[ module
].skip
!== null ) {
1109 // eslint-disable-next-line no-new-func
1110 skip
= new Function( registry
[ module
].skip
);
1111 registry
[ module
].skip
= null;
1113 registry
[ module
].skipped
= true;
1114 registry
[ module
].dependencies
= [];
1115 registry
[ module
].state
= 'ready';
1116 handlePending( module
);
1121 // Resolves dynamic loader function and replaces it with its own results
1122 if ( typeof registry
[ module
].dependencies
=== 'function' ) {
1123 registry
[ module
].dependencies
= registry
[ module
].dependencies();
1124 // Ensures the module's dependencies are always in an array
1125 if ( typeof registry
[ module
].dependencies
!== 'object' ) {
1126 registry
[ module
].dependencies
= [ registry
[ module
].dependencies
];
1129 if ( $.inArray( module
, resolved
) !== -1 ) {
1130 // Module already resolved; nothing to do
1133 // Create unresolved if not passed in
1134 if ( !unresolved
) {
1135 unresolved
= new StringSet();
1137 // Tracks down dependencies
1138 deps
= registry
[ module
].dependencies
;
1139 for ( i
= 0; i
< deps
.length
; i
++ ) {
1140 if ( $.inArray( deps
[ i
], resolved
) === -1 ) {
1141 if ( unresolved
.has( deps
[ i
] ) ) {
1142 throw new Error( mw
.format(
1143 'Circular reference detected: $1 -> $2',
1149 unresolved
.add( module
);
1150 sortDependencies( deps
[ i
], resolved
, unresolved
);
1153 resolved
.push( module
);
1157 * Get names of module that a module depends on, in their proper dependency order.
1160 * @param {string[]} modules Array of string module names
1161 * @return {Array} List of dependencies, including 'module'.
1162 * @throws {Error} If an unregistered module or a dependency loop is encountered
1164 function resolve( modules
) {
1165 var i
, resolved
= [];
1166 for ( i
= 0; i
< modules
.length
; i
++ ) {
1167 sortDependencies( modules
[ i
], resolved
);
1173 * Load and execute a script.
1176 * @param {string} src URL to script, will be used as the src attribute in the script tag
1177 * @return {jQuery.Promise}
1179 function addScript( src
) {
1183 // Force jQuery behaviour to be for crossDomain. Otherwise jQuery would use
1184 // XHR for a same domain request instead of <script>, which changes the request
1185 // headers (potentially missing a cache hit), and reduces caching in general
1186 // since browsers cache XHR much less (if at all). And XHR means we retrieve
1187 // text, so we'd need to $.globalEval, which then messes up line numbers.
1194 * Queue the loading and execution of a script for a particular module.
1197 * @param {string} src URL of the script
1198 * @param {string} [moduleName] Name of currently executing module
1199 * @return {jQuery.Promise}
1201 function queueModuleScript( src
, moduleName
) {
1202 var r
= $.Deferred();
1204 pendingRequests
.push( function () {
1205 if ( moduleName
&& hasOwn
.call( registry
, moduleName
) ) {
1206 // Emulate runScript() part of execute()
1207 window
.require
= mw
.loader
.require
;
1208 window
.module
= registry
[ moduleName
].module
;
1210 addScript( src
).always( function () {
1211 // 'module.exports' should not persist after the file is executed to
1212 // avoid leakage to unrelated code. 'require' should be kept, however,
1213 // as asynchronous access to 'require' is allowed and expected. (T144879)
1214 delete window
.module
;
1217 // Start the next one (if any)
1218 if ( pendingRequests
[ 0 ] ) {
1219 pendingRequests
.shift()();
1221 handlingPendingRequests
= false;
1225 if ( !handlingPendingRequests
&& pendingRequests
[ 0 ] ) {
1226 handlingPendingRequests
= true;
1227 pendingRequests
.shift()();
1233 * Utility function for execute()
1236 * @param {string} [media] Media attribute
1237 * @param {string} url URL
1239 function addLink( media
, url
) {
1240 var el
= document
.createElement( 'link' );
1242 el
.rel
= 'stylesheet';
1243 if ( media
&& media
!== 'all' ) {
1246 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1247 // see #addEmbeddedCSS, T33676, T43331, and T49277 for details.
1250 $( getMarker() ).before( el
);
1254 * Executes a loaded module, making it ready to use
1257 * @param {string} module Module name to execute
1259 function execute( module
) {
1260 var key
, value
, media
, i
, urls
, cssHandle
, checkCssHandles
, runScript
,
1261 cssHandlesRegistered
= false;
1263 if ( !hasOwn
.call( registry
, module
) ) {
1264 throw new Error( 'Module has not been registered yet: ' + module
);
1266 if ( registry
[ module
].state
!== 'loaded' ) {
1267 throw new Error( 'Module in state "' + registry
[ module
].state
+ '" may not be executed: ' + module
);
1270 registry
[ module
].state
= 'executing';
1272 runScript = function () {
1273 var script
, markModuleReady
, nestedAddScript
, implicitDependencies
, implicitWait
;
1275 script
= registry
[ module
].script
;
1276 markModuleReady = function () {
1277 registry
[ module
].state
= 'ready';
1278 handlePending( module
);
1280 nestedAddScript = function ( arr
, callback
, i
) {
1281 // Recursively call queueModuleScript() in its own callback
1282 // for each element of arr.
1283 if ( i
>= arr
.length
) {
1284 // We're at the end of the array
1289 queueModuleScript( arr
[ i
], module
).always( function () {
1290 nestedAddScript( arr
, callback
, i
+ 1 );
1294 implicitDependencies
= [];
1296 if ( module
=== 'user' ) {
1297 // Implicit dependency on the site module. Not real dependency because
1298 // it should run after 'site' regardless of whether it succeeds or fails.
1299 implicitDependencies
.push( 'site' );
1302 implicitWait
= implicitDependencies
.length
?
1303 mw
.loader
.using( implicitDependencies
) :
1304 $.Deferred().resolve();
1306 implicitWait
.always( function () {
1308 if ( Array
.isArray( script
) ) {
1309 nestedAddScript( script
, markModuleReady
, 0 );
1310 } else if ( typeof script
=== 'function' ) {
1311 // Pass jQuery twice so that the signature of the closure which wraps
1312 // the script can bind both '$' and 'jQuery'.
1313 script( $, $, mw
.loader
.require
, registry
[ module
].module
);
1316 } else if ( typeof script
=== 'string' ) {
1317 // Site and user modules are legacy scripts that run in the global scope.
1318 // This is transported as a string instead of a function to avoid needing
1319 // to use string manipulation to undo the function wrapper.
1320 $.globalEval( script
);
1324 // Module without script
1328 // Use mw.track instead of mw.log because these errors are common in production mode
1329 // (e.g. undefined variable), and mw.log is only enabled in debug mode.
1330 registry
[ module
].state
= 'error';
1331 mw
.track( 'resourceloader.exception', { exception
: e
, module
: module
, source
: 'module-execute' } );
1332 handlePending( module
);
1337 // Add localizations to message system
1338 if ( registry
[ module
].messages
) {
1339 mw
.messages
.set( registry
[ module
].messages
);
1342 // Initialise templates
1343 if ( registry
[ module
].templates
) {
1344 mw
.templates
.set( module
, registry
[ module
].templates
);
1347 // Make sure we don't run the scripts until all stylesheet insertions have completed.
1350 checkCssHandles = function () {
1351 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
1352 // one of the cssHandles is fired while we're still creating more handles.
1353 if ( cssHandlesRegistered
&& pending
=== 0 && runScript
) {
1355 runScript
= undefined; // Revoke
1358 cssHandle = function () {
1359 var check
= checkCssHandles
;
1361 return function () {
1365 check
= undefined; // Revoke
1371 // Process styles (see also mw.loader.implement)
1372 // * back-compat: { <media>: css }
1373 // * back-compat: { <media>: [url, ..] }
1374 // * { "css": [css, ..] }
1375 // * { "url": { <media>: [url, ..] } }
1376 if ( registry
[ module
].style
) {
1377 for ( key
in registry
[ module
].style
) {
1378 value
= registry
[ module
].style
[ key
];
1381 if ( key
!== 'url' && key
!== 'css' ) {
1382 // Backwards compatibility, key is a media-type
1383 if ( typeof value
=== 'string' ) {
1384 // back-compat: { <media>: css }
1385 // Ignore 'media' because it isn't supported (nor was it used).
1386 // Strings are pre-wrapped in "@media". The media-type was just ""
1387 // (because it had to be set to something).
1388 // This is one of the reasons why this format is no longer used.
1389 addEmbeddedCSS( value
, cssHandle() );
1391 // back-compat: { <media>: [url, ..] }
1397 // Array of css strings in key 'css',
1398 // or back-compat array of urls from media-type
1399 if ( Array
.isArray( value
) ) {
1400 for ( i
= 0; i
< value
.length
; i
++ ) {
1401 if ( key
=== 'bc-url' ) {
1402 // back-compat: { <media>: [url, ..] }
1403 addLink( media
, value
[ i
] );
1404 } else if ( key
=== 'css' ) {
1405 // { "css": [css, ..] }
1406 addEmbeddedCSS( value
[ i
], cssHandle() );
1409 // Not an array, but a regular object
1410 // Array of urls inside media-type key
1411 } else if ( typeof value
=== 'object' ) {
1412 // { "url": { <media>: [url, ..] } }
1413 for ( media
in value
) {
1414 urls
= value
[ media
];
1415 for ( i
= 0; i
< urls
.length
; i
++ ) {
1416 addLink( media
, urls
[ i
] );
1424 cssHandlesRegistered
= true;
1429 * Add one or more modules to the module load queue.
1434 * @param {string|string[]} dependencies Module name or array of string module names
1435 * @param {Function} [ready] Callback to execute when all dependencies are ready
1436 * @param {Function} [error] Callback to execute when any dependency fails
1438 function enqueue( dependencies
, ready
, error
) {
1439 // Allow calling by single module name
1440 if ( typeof dependencies
=== 'string' ) {
1441 dependencies
= [ dependencies
];
1444 // Add ready and error callbacks if they were given
1445 if ( ready
!== undefined || error
!== undefined ) {
1447 // Narrow down the list to modules that are worth waiting for
1448 dependencies
: $.grep( dependencies
, function ( module
) {
1449 var state
= mw
.loader
.getState( module
);
1450 return state
=== 'registered' || state
=== 'loaded' || state
=== 'loading' || state
=== 'executing';
1457 $.each( dependencies
, function ( idx
, module
) {
1458 var state
= mw
.loader
.getState( module
);
1459 // Only queue modules that are still in the initial 'registered' state
1460 // (not ones already loading, ready or error).
1461 if ( state
=== 'registered' && $.inArray( module
, queue
) === -1 ) {
1462 // Private modules must be embedded in the page. Don't bother queuing
1463 // these as the server will deny them anyway (T101806).
1464 if ( registry
[ module
].group
=== 'private' ) {
1465 registry
[ module
].state
= 'error';
1466 handlePending( module
);
1469 queue
.push( module
);
1476 function sortQuery( o
) {
1482 if ( hasOwn
.call( o
, key
) ) {
1487 for ( key
= 0; key
< a
.length
; key
++ ) {
1488 sorted
[ a
[ key
] ] = o
[ a
[ key
] ];
1494 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
1495 * to a query string of the form foo.bar,baz|bar.baz,quux
1498 * @param {Object} moduleMap Module map
1499 * @return {string} Module query string
1501 function buildModulesString( moduleMap
) {
1505 for ( prefix
in moduleMap
) {
1506 p
= prefix
=== '' ? '' : prefix
+ '.';
1507 arr
.push( p
+ moduleMap
[ prefix
].join( ',' ) );
1509 return arr
.join( '|' );
1513 * Make a network request to load modules from the server.
1516 * @param {Object} moduleMap Module map, see #buildModulesString
1517 * @param {Object} currReqBase Object with other parameters (other than 'modules') to use in the request
1518 * @param {string} sourceLoadScript URL of load.php
1520 function doRequest( moduleMap
, currReqBase
, sourceLoadScript
) {
1521 var query
= $.extend(
1522 { modules
: buildModulesString( moduleMap
) },
1525 query
= sortQuery( query
);
1526 addScript( sourceLoadScript
+ '?' + $.param( query
) );
1530 * Resolve indexed dependencies.
1532 * ResourceLoader uses an optimization to save space which replaces module names in
1533 * dependency lists with the index of that module within the array of module
1534 * registration data if it exists. The benefit is a significant reduction in the data
1535 * size of the startup module. This function changes those dependency lists back to
1536 * arrays of strings.
1539 * @param {Array} modules Modules array
1541 function resolveIndexedDependencies( modules
) {
1543 function resolveIndex( dep
) {
1544 return typeof dep
=== 'number' ? modules
[ dep
][ 0 ] : dep
;
1546 for ( i
= 0; i
< modules
.length
; i
++ ) {
1547 deps
= modules
[ i
][ 2 ];
1549 for ( j
= 0; j
< deps
.length
; j
++ ) {
1550 deps
[ j
] = resolveIndex( deps
[ j
] );
1557 * Create network requests for a batch of modules.
1559 * This is an internal method for #work(). This must not be called directly
1560 * unless the modules are already registered, and no request is in progress,
1561 * and the module state has already been set to `loading`.
1564 * @param {string[]} batch
1566 function batchRequest( batch
) {
1567 var reqBase
, splits
, maxQueryLength
, b
, bSource
, bGroup
, bSourceGroup
,
1568 source
, group
, i
, modules
, sourceLoadScript
,
1569 currReqBase
, currReqBaseLength
, moduleMap
, l
,
1570 lastDotIndex
, prefix
, suffix
, bytesAdded
;
1572 if ( !batch
.length
) {
1576 // Always order modules alphabetically to help reduce cache
1577 // misses for otherwise identical content.
1580 // Build a list of query parameters common to all requests
1582 skin
: mw
.config
.get( 'skin' ),
1583 lang
: mw
.config
.get( 'wgUserLanguage' ),
1584 debug
: mw
.config
.get( 'debug' )
1586 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', 2000 );
1588 // Split module list by source and by group.
1590 for ( b
= 0; b
< batch
.length
; b
++ ) {
1591 bSource
= registry
[ batch
[ b
] ].source
;
1592 bGroup
= registry
[ batch
[ b
] ].group
;
1593 if ( !hasOwn
.call( splits
, bSource
) ) {
1594 splits
[ bSource
] = {};
1596 if ( !hasOwn
.call( splits
[ bSource
], bGroup
) ) {
1597 splits
[ bSource
][ bGroup
] = [];
1599 bSourceGroup
= splits
[ bSource
][ bGroup
];
1600 bSourceGroup
.push( batch
[ b
] );
1603 for ( source
in splits
) {
1605 sourceLoadScript
= sources
[ source
];
1607 for ( group
in splits
[ source
] ) {
1609 // Cache access to currently selected list of
1610 // modules for this group from this source.
1611 modules
= splits
[ source
][ group
];
1613 currReqBase
= $.extend( {
1614 version
: getCombinedVersion( modules
)
1616 // For user modules append a user name to the query string.
1617 if ( group
=== 'user' && mw
.config
.get( 'wgUserName' ) !== null ) {
1618 currReqBase
.user
= mw
.config
.get( 'wgUserName' );
1620 currReqBaseLength
= $.param( currReqBase
).length
;
1621 // We may need to split up the request to honor the query string length limit,
1622 // so build it piece by piece.
1623 l
= currReqBaseLength
+ 9; // '&modules='.length == 9
1625 moduleMap
= {}; // { prefix: [ suffixes ] }
1627 for ( i
= 0; i
< modules
.length
; i
++ ) {
1628 // Determine how many bytes this module would add to the query string
1629 lastDotIndex
= modules
[ i
].lastIndexOf( '.' );
1631 // If lastDotIndex is -1, substr() returns an empty string
1632 prefix
= modules
[ i
].substr( 0, lastDotIndex
);
1633 suffix
= modules
[ i
].slice( lastDotIndex
+ 1 );
1635 bytesAdded
= hasOwn
.call( moduleMap
, prefix
) ?
1636 suffix
.length
+ 3 : // '%2C'.length == 3
1637 modules
[ i
].length
+ 3; // '%7C'.length == 3
1639 // If the url would become too long, create a new one,
1640 // but don't create empty requests
1641 if ( maxQueryLength
> 0 && !$.isEmptyObject( moduleMap
) && l
+ bytesAdded
> maxQueryLength
) {
1642 // This url would become too long, create a new one, and start the old one
1643 doRequest( moduleMap
, currReqBase
, sourceLoadScript
);
1645 l
= currReqBaseLength
+ 9;
1646 mw
.track( 'resourceloader.splitRequest', { maxQueryLength
: maxQueryLength
} );
1648 if ( !hasOwn
.call( moduleMap
, prefix
) ) {
1649 moduleMap
[ prefix
] = [];
1651 moduleMap
[ prefix
].push( suffix
);
1654 // If there's anything left in moduleMap, request that too
1655 if ( !$.isEmptyObject( moduleMap
) ) {
1656 doRequest( moduleMap
, currReqBase
, sourceLoadScript
);
1664 * @param {string[]} implementations Array containing pieces of JavaScript code in the
1665 * form of calls to mw.loader#implement().
1666 * @param {Function} cb Callback in case of failure
1667 * @param {Error} cb.err
1669 function asyncEval( implementations
, cb
) {
1670 if ( !implementations
.length
) {
1673 mw
.requestIdleCallback( function () {
1675 $.globalEval( implementations
.join( ';' ) );
1683 * Make a versioned key for a specific module.
1686 * @param {string} module Module name
1687 * @return {string|null} Module key in format '`[name]@[version]`',
1688 * or null if the module does not exist
1690 function getModuleKey( module
) {
1691 return hasOwn
.call( registry
, module
) ?
1692 ( module
+ '@' + registry
[ module
].version
) : null;
1697 * @param {string} key Module name or '`[name]@[version]`'
1700 function splitModuleKey( key
) {
1701 var index
= key
.indexOf( '@' );
1702 if ( index
=== -1 ) {
1703 return { name
: key
};
1706 name
: key
.slice( 0, index
),
1707 version
: key
.slice( index
+ 1 )
1711 /* Public Members */
1714 * The module registry is exposed as an aid for debugging and inspecting page
1715 * state; it is not a public interface for modifying the registry.
1721 moduleRegistry
: registry
,
1724 * @inheritdoc #newStyleTag
1727 addStyleTag
: newStyleTag
,
1730 * Start loading of all queued module dependencies.
1735 var q
, batch
, implementations
, sourceModules
;
1739 // Appends a list of modules from the queue to the batch
1740 for ( q
= 0; q
< queue
.length
; q
++ ) {
1741 // Only load modules which are registered
1742 if ( hasOwn
.call( registry
, queue
[ q
] ) && registry
[ queue
[ q
] ].state
=== 'registered' ) {
1743 // Prevent duplicate entries
1744 if ( $.inArray( queue
[ q
], batch
) === -1 ) {
1745 batch
.push( queue
[ q
] );
1746 // Mark registered modules as loading
1747 registry
[ queue
[ q
] ].state
= 'loading';
1752 // Now that the queue has been processed into a batch, clear the queue.
1753 // This MUST happen before we initiate any eval or network request. Otherwise,
1754 // it is possible for a cached script to instantly trigger the same work queue
1755 // again; all before we've cleared it causing each request to include modules
1756 // which are already loaded.
1759 if ( !batch
.length
) {
1763 mw
.loader
.store
.init();
1764 if ( mw
.loader
.store
.enabled
) {
1765 implementations
= [];
1767 batch
= $.grep( batch
, function ( module
) {
1768 var implementation
= mw
.loader
.store
.get( module
);
1769 if ( implementation
) {
1770 implementations
.push( implementation
);
1771 sourceModules
.push( module
);
1776 asyncEval( implementations
, function ( err
) {
1778 // Not good, the cached mw.loader.implement calls failed! This should
1779 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1780 // Depending on how corrupt the string is, it is likely that some
1781 // modules' implement() succeeded while the ones after the error will
1782 // never run and leave their modules in the 'loading' state forever.
1783 mw
.loader
.store
.stats
.failed
++;
1785 // Since this is an error not caused by an individual module but by
1786 // something that infected the implement call itself, don't take any
1787 // risks and clear everything in this cache.
1788 mw
.loader
.store
.clear();
1790 mw
.track( 'resourceloader.exception', { exception
: err
, source
: 'store-eval' } );
1791 // Re-add the failed ones that are still pending back to the batch
1792 failed
= $.grep( sourceModules
, function ( module
) {
1793 return registry
[ module
].state
=== 'loading';
1795 batchRequest( failed
);
1799 batchRequest( batch
);
1803 * Register a source.
1805 * The #work() method will use this information to split up requests by source.
1807 * mw.loader.addSource( 'mediawikiwiki', '//www.mediawiki.org/w/load.php' );
1809 * @param {string|Object} id Source ID, or object mapping ids to load urls
1810 * @param {string} loadUrl Url to a load.php end point
1811 * @throws {Error} If source id is already registered
1813 addSource: function ( id
, loadUrl
) {
1815 // Allow multiple additions
1816 if ( typeof id
=== 'object' ) {
1817 for ( source
in id
) {
1818 mw
.loader
.addSource( source
, id
[ source
] );
1823 if ( hasOwn
.call( sources
, id
) ) {
1824 throw new Error( 'source already registered: ' + id
);
1827 sources
[ id
] = loadUrl
;
1831 * Register a module, letting the system know about it and its properties.
1833 * The startup modules contain calls to this method.
1835 * When using multiple module registration by passing an array, dependencies that
1836 * are specified as references to modules within the array will be resolved before
1837 * the modules are registered.
1839 * @param {string|Array} module Module name or array of arrays, each containing
1840 * a list of arguments compatible with this method
1841 * @param {string|number} version Module version hash (falls backs to empty string)
1842 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1843 * @param {string|Array|Function} dependencies One string or array of strings of module
1844 * names on which this module depends, or a function that returns that array.
1845 * @param {string} [group=null] Group which the module is in
1846 * @param {string} [source='local'] Name of the source
1847 * @param {string} [skip=null] Script body of the skip function
1849 register: function ( module
, version
, dependencies
, group
, source
, skip
) {
1851 // Allow multiple registration
1852 if ( typeof module
=== 'object' ) {
1853 resolveIndexedDependencies( module
);
1854 for ( i
= 0; i
< module
.length
; i
++ ) {
1855 // module is an array of module names
1856 if ( typeof module
[ i
] === 'string' ) {
1857 mw
.loader
.register( module
[ i
] );
1858 // module is an array of arrays
1859 } else if ( typeof module
[ i
] === 'object' ) {
1860 mw
.loader
.register
.apply( mw
.loader
, module
[ i
] );
1865 if ( hasOwn
.call( registry
, module
) ) {
1866 throw new Error( 'module already registered: ' + module
);
1868 if ( typeof dependencies
=== 'string' ) {
1869 // A single module name
1870 deps
= [ dependencies
];
1871 } else if ( typeof dependencies
=== 'object' || typeof dependencies
=== 'function' ) {
1872 // Array of module names or a function that returns an array
1873 deps
= dependencies
;
1875 // List the module as registered
1876 registry
[ module
] = {
1877 // Exposed to execute() for mw.loader.implement() closures.
1878 // Import happens via require().
1882 version
: version
!== undefined ? String( version
) : '',
1883 dependencies
: deps
|| [],
1884 group
: typeof group
=== 'string' ? group
: null,
1885 source
: typeof source
=== 'string' ? source
: 'local',
1886 state
: 'registered',
1887 skip
: typeof skip
=== 'string' ? skip
: null
1892 * Implement a module given the components that make up the module.
1894 * When #load() or #using() requests one or more modules, the server
1895 * response contain calls to this function.
1897 * @param {string} module Name of module and current module version. Formatted
1898 * as '`[name]@[version]`". This version should match the requested version
1899 * (from #batchRequest and #registry). This avoids race conditions (T117587).
1900 * For back-compat with MediaWiki 1.27 and earlier, the version may be omitted.
1901 * @param {Function|Array|string} [script] Function with module code, list of URLs
1902 * to load via `<script src>`, or string of module code for `$.globalEval()`.
1903 * @param {Object} [style] Should follow one of the following patterns:
1905 * { "css": [css, ..] }
1906 * { "url": { <media>: [url, ..] } }
1908 * And for backwards compatibility (needs to be supported forever due to caching):
1911 * { <media>: [url, ..] }
1913 * The reason css strings are not concatenated anymore is T33676. We now check
1914 * whether it's safe to extend the stylesheet.
1917 * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1918 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1920 implement: function ( module
, script
, style
, messages
, templates
) {
1921 var split
= splitModuleKey( module
),
1923 version
= split
.version
;
1924 // Automatically register module
1925 if ( !hasOwn
.call( registry
, name
) ) {
1926 mw
.loader
.register( name
);
1928 // Check for duplicate implementation
1929 if ( hasOwn
.call( registry
, name
) && registry
[ name
].script
!== undefined ) {
1930 throw new Error( 'module already implemented: ' + name
);
1933 // Without this reset, if there is a version mismatch between the
1934 // requested and received module version, then mw.loader.store would
1935 // cache the response under the requested key. Thus poisoning the cache
1936 // indefinitely with a stale value. (T117587)
1937 registry
[ name
].version
= version
;
1939 // Attach components
1940 registry
[ name
].script
= script
|| null;
1941 registry
[ name
].style
= style
|| null;
1942 registry
[ name
].messages
= messages
|| null;
1943 registry
[ name
].templates
= templates
|| null;
1944 // The module may already have been marked as erroneous
1945 if ( $.inArray( registry
[ name
].state
, [ 'error', 'missing' ] ) === -1 ) {
1946 registry
[ name
].state
= 'loaded';
1947 if ( allReady( registry
[ name
].dependencies
) ) {
1954 * Execute a function as soon as one or more required modules are ready.
1956 * Example of inline dependency on OOjs:
1958 * mw.loader.using( 'oojs', function () {
1959 * OO.compare( [ 1 ], [ 1 ] );
1962 * Since MediaWiki 1.23 this also returns a promise.
1964 * Since MediaWiki 1.28 the promise is resolved with a `require` function.
1966 * @param {string|Array} dependencies Module name or array of modules names the
1967 * callback depends on to be ready before executing
1968 * @param {Function} [ready] Callback to execute when all dependencies are ready
1969 * @param {Function} [error] Callback to execute if one or more dependencies failed
1970 * @return {jQuery.Promise} With a `require` function
1972 using: function ( dependencies
, ready
, error
) {
1973 var deferred
= $.Deferred();
1975 // Allow calling with a single dependency as a string
1976 if ( typeof dependencies
=== 'string' ) {
1977 dependencies
= [ dependencies
];
1981 deferred
.done( ready
);
1984 deferred
.fail( error
);
1988 // Resolve entire dependency map
1989 dependencies
= resolve( dependencies
);
1991 return deferred
.reject( e
).promise();
1993 if ( allReady( dependencies
) ) {
1994 // Run ready immediately
1995 deferred
.resolve( mw
.loader
.require
);
1996 } else if ( anyFailed( dependencies
) ) {
1997 // Execute error immediately if any dependencies have errors
1999 new Error( 'One or more dependencies failed to load' ),
2003 // Not all dependencies are ready, add to the load queue
2004 enqueue( dependencies
, function () {
2005 deferred
.resolve( mw
.loader
.require
);
2006 }, deferred
.reject
);
2009 return deferred
.promise();
2013 * Load an external script or one or more modules.
2015 * @param {string|Array} modules Either the name of a module, array of modules,
2016 * or a URL of an external script or style
2017 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
2018 * external script or style; acceptable values are "text/css" and
2019 * "text/javascript"; if no type is provided, text/javascript is assumed.
2021 load: function ( modules
, type
) {
2024 // Allow calling with a url or single dependency as a string
2025 if ( typeof modules
=== 'string' ) {
2026 // "https://example.org/x.js", "http://example.org/x.js", "//example.org/x.js", "/x.js"
2027 if ( /^(https?:)?\/?\//.test( modules
) ) {
2028 if ( type
=== 'text/css' ) {
2029 l
= document
.createElement( 'link' );
2030 l
.rel
= 'stylesheet';
2032 $( 'head' ).append( l
);
2035 if ( type
=== 'text/javascript' || type
=== undefined ) {
2036 addScript( modules
);
2040 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type
);
2042 // Called with single module
2043 modules
= [ modules
];
2046 // Filter out undefined modules, otherwise resolve() will throw
2047 // an exception for trying to load an undefined module.
2048 // Undefined modules are acceptable here in load(), because load() takes
2049 // an array of unrelated modules, whereas the modules passed to
2050 // using() are related and must all be loaded.
2051 filtered
= $.grep( modules
, function ( module
) {
2052 var state
= mw
.loader
.getState( module
);
2053 return state
!== null && state
!== 'error' && state
!== 'missing';
2056 if ( filtered
.length
=== 0 ) {
2059 // Resolve entire dependency map
2060 filtered
= resolve( filtered
);
2061 // If all modules are ready, or if any modules have errors, nothing to be done.
2062 if ( allReady( filtered
) || anyFailed( filtered
) ) {
2065 // Some modules are not yet ready, add to module load queue.
2066 enqueue( filtered
, undefined, undefined );
2070 * Change the state of one or more modules.
2072 * @param {string|Object} module Module name or object of module name/state pairs
2073 * @param {string} state State name
2075 state: function ( module
, state
) {
2078 if ( typeof module
=== 'object' ) {
2079 for ( m
in module
) {
2080 mw
.loader
.state( m
, module
[ m
] );
2084 if ( !hasOwn
.call( registry
, module
) ) {
2085 mw
.loader
.register( module
);
2087 registry
[ module
].state
= state
;
2088 if ( $.inArray( state
, [ 'ready', 'error', 'missing' ] ) !== -1 ) {
2089 // Make sure pending modules depending on this one get executed if their
2090 // dependencies are now fulfilled!
2091 handlePending( module
);
2096 * Get the version of a module.
2098 * @param {string} module Name of module
2099 * @return {string|null} The version, or null if the module (or its version) is not
2102 getVersion: function ( module
) {
2103 if ( !hasOwn
.call( registry
, module
) || registry
[ module
].version
=== undefined ) {
2106 return registry
[ module
].version
;
2110 * Get the state of a module.
2112 * @param {string} module Name of module
2113 * @return {string|null} The state, or null if the module (or its state) is not
2116 getState: function ( module
) {
2117 if ( !hasOwn
.call( registry
, module
) || registry
[ module
].state
=== undefined ) {
2120 return registry
[ module
].state
;
2124 * Get the names of all registered modules.
2128 getModuleNames: function () {
2129 return Object
.keys( registry
);
2133 * Get the exported value of a module.
2135 * Modules may provide this via their local `module.exports`.
2139 * @param {string} moduleName Module name
2140 * @return {Mixed} Exported value
2142 require: function ( moduleName
) {
2143 var state
= mw
.loader
.getState( moduleName
);
2145 // Only ready modules can be required
2146 if ( state
!== 'ready' ) {
2147 // Module may've forgotten to declare a dependency
2148 throw new Error( 'Module "' + moduleName
+ '" is not loaded.' );
2151 return registry
[ moduleName
].module
.exports
;
2155 * @inheritdoc mw.inspect#runReports
2158 inspect: function () {
2159 var args
= slice
.call( arguments
);
2160 mw
.loader
.using( 'mediawiki.inspect', function () {
2161 mw
.inspect
.runReports
.apply( mw
.inspect
, args
);
2166 * On browsers that implement the localStorage API, the module store serves as a
2167 * smart complement to the browser cache. Unlike the browser cache, the module store
2168 * can slice a concatenated response from ResourceLoader into its constituent
2169 * modules and cache each of them separately, using each module's versioning scheme
2170 * to determine when the cache should be invalidated.
2173 * @class mw.loader.store
2176 // Whether the store is in use on this page.
2179 // Modules whose string representation exceeds 100 kB are
2180 // ineligible for storage. See bug T66721.
2181 MODULE_SIZE_MAX
: 100 * 1000,
2183 // The contents of the store, mapping '[name]@[version]' keys
2184 // to module implementations.
2188 stats
: { hits
: 0, misses
: 0, expired
: 0, failed
: 0 },
2191 * Construct a JSON-serializable object representing the content of the store.
2193 * @return {Object} Module store contents.
2195 toJSON: function () {
2196 return { items
: mw
.loader
.store
.items
, vary
: mw
.loader
.store
.getVary() };
2200 * Get the localStorage key for the entire module store. The key references
2201 * $wgDBname to prevent clashes between wikis which share a common host.
2203 * @return {string} localStorage item key
2205 getStoreKey: function () {
2206 return 'MediaWikiModuleStore:' + mw
.config
.get( 'wgDBname' );
2210 * Get a key on which to vary the module cache.
2212 * @return {string} String of concatenated vary conditions.
2214 getVary: function () {
2216 mw
.config
.get( 'skin' ),
2217 mw
.config
.get( 'wgResourceLoaderStorageVersion' ),
2218 mw
.config
.get( 'wgUserLanguage' )
2223 * Initialize the store.
2225 * Retrieves store from localStorage and (if successfully retrieved) decoding
2226 * the stored JSON value to a plain object.
2228 * The try / catch block is used for JSON & localStorage feature detection.
2229 * See the in-line documentation for Modernizr's localStorage feature detection
2230 * code for a full account of why we need a try / catch:
2231 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2236 if ( mw
.loader
.store
.enabled
!== null ) {
2242 // Disabled because localStorage quotas are tight and (in Firefox's case)
2243 // shared by multiple origins.
2244 // See T66721, and <https://bugzilla.mozilla.org/show_bug.cgi?id=1064466>.
2245 /Firefox|Opera/.test( navigator
.userAgent
) ||
2247 // Disabled by configuration.
2248 !mw
.config
.get( 'wgResourceLoaderStorageEnabled' )
2250 // Clear any previous store to free up space. (T66721)
2251 mw
.loader
.store
.clear();
2252 mw
.loader
.store
.enabled
= false;
2255 if ( mw
.config
.get( 'debug' ) ) {
2256 // Disable module store in debug mode
2257 mw
.loader
.store
.enabled
= false;
2262 raw
= localStorage
.getItem( mw
.loader
.store
.getStoreKey() );
2263 // If we get here, localStorage is available; mark enabled
2264 mw
.loader
.store
.enabled
= true;
2265 data
= JSON
.parse( raw
);
2266 if ( data
&& typeof data
.items
=== 'object' && data
.vary
=== mw
.loader
.store
.getVary() ) {
2267 mw
.loader
.store
.items
= data
.items
;
2271 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-init' } );
2274 if ( raw
=== undefined ) {
2275 // localStorage failed; disable store
2276 mw
.loader
.store
.enabled
= false;
2278 mw
.loader
.store
.update();
2283 * Retrieve a module from the store and update cache hit stats.
2285 * @param {string} module Module name
2286 * @return {string|boolean} Module implementation or false if unavailable
2288 get: function ( module
) {
2291 if ( !mw
.loader
.store
.enabled
) {
2295 key
= getModuleKey( module
);
2296 if ( key
in mw
.loader
.store
.items
) {
2297 mw
.loader
.store
.stats
.hits
++;
2298 return mw
.loader
.store
.items
[ key
];
2300 mw
.loader
.store
.stats
.misses
++;
2305 * Stringify a module and queue it for storage.
2307 * @param {string} module Module name
2308 * @param {Object} descriptor The module's descriptor as set in the registry
2309 * @return {boolean} Module was set
2311 set: function ( module
, descriptor
) {
2314 if ( !mw
.loader
.store
.enabled
) {
2318 key
= getModuleKey( module
);
2321 // Already stored a copy of this exact version
2322 key
in mw
.loader
.store
.items
||
2323 // Module failed to load
2324 descriptor
.state
!== 'ready' ||
2325 // Unversioned, private, or site-/user-specific
2326 ( !descriptor
.version
|| $.inArray( descriptor
.group
, [ 'private', 'user' ] ) !== -1 ) ||
2327 // Partial descriptor
2328 // (e.g. skipped module, or style module with state=ready)
2329 $.inArray( undefined, [ descriptor
.script
, descriptor
.style
,
2330 descriptor
.messages
, descriptor
.templates
] ) !== -1
2338 JSON
.stringify( key
),
2339 typeof descriptor
.script
=== 'function' ?
2340 String( descriptor
.script
) :
2341 JSON
.stringify( descriptor
.script
),
2342 JSON
.stringify( descriptor
.style
),
2343 JSON
.stringify( descriptor
.messages
),
2344 JSON
.stringify( descriptor
.templates
)
2346 // Attempted workaround for a possible Opera bug (bug T59567).
2347 // This regex should never match under sane conditions.
2348 if ( /^\s*\(/.test( args
[ 1 ] ) ) {
2349 args
[ 1 ] = 'function' + args
[ 1 ];
2350 mw
.track( 'resourceloader.assert', { source
: 'bug-T59567' } );
2353 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-json' } );
2357 src
= 'mw.loader.implement(' + args
.join( ',' ) + ');';
2358 if ( src
.length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2361 mw
.loader
.store
.items
[ key
] = src
;
2362 mw
.loader
.store
.update();
2367 * Iterate through the module store, removing any item that does not correspond
2368 * (in name and version) to an item in the module registry.
2370 * @return {boolean} Store was pruned
2372 prune: function () {
2375 if ( !mw
.loader
.store
.enabled
) {
2379 for ( key
in mw
.loader
.store
.items
) {
2380 module
= key
.slice( 0, key
.indexOf( '@' ) );
2381 if ( getModuleKey( module
) !== key
) {
2382 mw
.loader
.store
.stats
.expired
++;
2383 delete mw
.loader
.store
.items
[ key
];
2384 } else if ( mw
.loader
.store
.items
[ key
].length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2385 // This value predates the enforcement of a size limit on cached modules.
2386 delete mw
.loader
.store
.items
[ key
];
2393 * Clear the entire module store right now.
2395 clear: function () {
2396 mw
.loader
.store
.items
= {};
2398 localStorage
.removeItem( mw
.loader
.store
.getStoreKey() );
2399 } catch ( ignored
) {}
2403 * Sync in-memory store back to localStorage.
2405 * This function debounces updates. When called with a flush already pending,
2406 * the call is coalesced into the pending update. The call to
2407 * localStorage.setItem will be naturally deferred until the page is quiescent.
2409 * Because localStorage is shared by all pages from the same origin, if multiple
2410 * pages are loaded with different module sets, the possibility exists that
2411 * modules saved by one page will be clobbered by another. But the impact would
2412 * be minor and the problem would be corrected by subsequent page views.
2416 update
: ( function () {
2417 var hasPendingWrite
= false;
2419 function flushWrites() {
2421 if ( !hasPendingWrite
|| !mw
.loader
.store
.enabled
) {
2425 mw
.loader
.store
.prune();
2426 key
= mw
.loader
.store
.getStoreKey();
2428 // Replacing the content of the module store might fail if the new
2429 // contents would exceed the browser's localStorage size limit. To
2430 // avoid clogging the browser with stale data, always remove the old
2431 // value before attempting to set the new one.
2432 localStorage
.removeItem( key
);
2433 data
= JSON
.stringify( mw
.loader
.store
);
2434 localStorage
.setItem( key
, data
);
2436 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-update' } );
2439 hasPendingWrite
= false;
2442 return function () {
2443 if ( !hasPendingWrite
) {
2444 hasPendingWrite
= true;
2445 mw
.requestIdleCallback( flushWrites
);
2454 * HTML construction helper functions
2461 * output = Html.element( 'div', {}, new Html.Raw(
2462 * Html.element( 'img', { src: '<' } )
2464 * mw.log( output ); // <div><img src="<"/></div>
2469 html
: ( function () {
2470 function escapeCallback( s
) {
2487 * Escape a string for HTML.
2489 * Converts special characters to HTML entities.
2491 * mw.html.escape( '< > \' & "' );
2492 * // Returns < > ' & "
2494 * @param {string} s The string to escape
2495 * @return {string} HTML
2497 escape: function ( s
) {
2498 return s
.replace( /['"<>&]/g, escapeCallback
);
2502 * Create an HTML element string, with safe escaping.
2504 * @param {string} name The tag name.
2505 * @param {Object} [attrs] An object with members mapping element names to values
2506 * @param {string|mw.html.Raw|mw.html.Cdata|null} [contents=null] The contents of the element.
2508 * - string: Text to be escaped.
2509 * - null: The element is treated as void with short closing form, e.g. `<br/>`.
2510 * - this.Raw: The raw value is directly included.
2511 * - this.Cdata: The raw value is directly included. An exception is
2512 * thrown if it contains any illegal ETAGO delimiter.
2513 * See <https://www.w3.org/TR/html401/appendix/notes.html#h-B.3.2>.
2514 * @return {string} HTML
2516 element: function ( name
, attrs
, contents
) {
2517 var v
, attrName
, s
= '<' + name
;
2520 for ( attrName
in attrs
) {
2521 v
= attrs
[ attrName
];
2522 // Convert name=true, to name=name
2526 } else if ( v
=== false ) {
2529 s
+= ' ' + attrName
+ '="' + this.escape( String( v
) ) + '"';
2532 if ( contents
=== undefined || contents
=== null ) {
2539 switch ( typeof contents
) {
2542 s
+= this.escape( contents
);
2546 // Convert to string
2547 s
+= String( contents
);
2550 if ( contents
instanceof this.Raw
) {
2551 // Raw HTML inclusion
2552 s
+= contents
.value
;
2553 } else if ( contents
instanceof this.Cdata
) {
2555 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
2556 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
2558 s
+= contents
.value
;
2560 throw new Error( 'mw.html.element: Invalid type of contents' );
2563 s
+= '</' + name
+ '>';
2568 * Wrapper object for raw HTML passed to mw.html.element().
2570 * @class mw.html.Raw
2572 * @param {string} value
2574 Raw: function ( value
) {
2579 * Wrapper object for CDATA element contents passed to mw.html.element()
2581 * @class mw.html.Cdata
2583 * @param {string} value
2585 Cdata: function ( value
) {
2591 // Skeleton user object, extended by the 'mediawiki.user' module.
2598 * @property {mw.Map}
2602 * @property {mw.Map}
2607 // OOUI widgets specific to MediaWiki
2611 * Registry and firing of events.
2613 * MediaWiki has various interface components that are extended, enhanced
2614 * or manipulated in some other way by extensions, gadgets and even
2617 * This framework helps streamlining the timing of when these other
2618 * code paths fire their plugins (instead of using document-ready,
2619 * which can and should be limited to firing only once).
2621 * Features like navigating to other wiki pages, previewing an edit
2622 * and editing itself – without a refresh – can then retrigger these
2623 * hooks accordingly to ensure everything still works as expected.
2627 * mw.hook( 'wikipage.content' ).add( fn ).remove( fn );
2628 * mw.hook( 'wikipage.content' ).fire( $content );
2630 * Handlers can be added and fired for arbitrary event names at any time. The same
2631 * event can be fired multiple times. The last run of an event is memorized
2632 * (similar to `$(document).ready` and `$.Deferred().done`).
2633 * This means if an event is fired, and a handler added afterwards, the added
2634 * function will be fired right away with the last given event data.
2636 * Like Deferreds and Promises, the mw.hook object is both detachable and chainable.
2637 * Thus allowing flexible use and optimal maintainability and authority control.
2638 * You can pass around the `add` and/or `fire` method to another piece of code
2639 * without it having to know the event name (or `mw.hook` for that matter).
2641 * var h = mw.hook( 'bar.ready' );
2642 * new mw.Foo( .. ).fetch( { callback: h.fire } );
2644 * Note: Events are documented with an underscore instead of a dot in the event
2645 * name due to jsduck not supporting dots in that position.
2649 hook
: ( function () {
2653 * Create an instance of mw.hook.
2657 * @param {string} name Name of hook.
2660 return function ( name
) {
2661 var list
= hasOwn
.call( lists
, name
) ?
2663 lists
[ name
] = $.Callbacks( 'memory' );
2667 * Register a hook handler
2669 * @param {...Function} handler Function to bind.
2675 * Unregister a hook handler
2677 * @param {...Function} handler Function to unbind.
2680 remove
: list
.remove
,
2682 // eslint-disable-next-line valid-jsdoc
2686 * @param {...Mixed} data
2690 return list
.fireWith
.call( this, null, slice
.call( arguments
) );
2697 // Alias $j to jQuery for backwards compatibility
2698 // @deprecated since 1.23 Use $ or jQuery instead
2699 mw
.log
.deprecate( window
, '$j', $, 'Use $ or jQuery instead.' );
2702 * Log a message to window.console, if possible.
2704 * Useful to force logging of some errors that are otherwise hard to detect (i.e., this logs
2705 * also in production mode). Gets console references in each invocation instead of caching the
2706 * reference, so that debugging tools loaded later are supported (e.g. Firebug Lite in IE).
2709 * @param {string} topic Stream name passed by mw.track
2710 * @param {Object} data Data passed by mw.track
2711 * @param {Error} [data.exception]
2712 * @param {string} data.source Error source
2713 * @param {string} [data.module] Name of module which caused the error
2715 function logError( topic
, data
) {
2716 /* eslint-disable no-console */
2719 source
= data
.source
,
2720 module
= data
.module
,
2721 console
= window
.console
;
2723 if ( console
&& console
.log
) {
2724 msg
= ( e
? 'Exception' : 'Error' ) + ' in ' + source
;
2726 msg
+= ' in module ' + module
;
2728 msg
+= ( e
? ':' : '.' );
2731 // If we have an exception object, log it to the error channel to trigger
2732 // proper stacktraces in browsers that support it. No fallback as we have
2733 // no browsers that don't support error(), but do support log().
2734 if ( e
&& console
.error
) {
2735 console
.error( String( e
), e
);
2738 /* eslint-enable no-console */
2741 // Subscribe to error streams
2742 mw
.trackSubscribe( 'resourceloader.exception', logError
);
2743 mw
.trackSubscribe( 'resourceloader.assert', logError
);
2746 * Fired when all modules associated with the page have finished loading.
2748 * @event resourceloader_loadEnd
2752 var loading
, modules
;
2754 modules
= $.grep( mw
.loader
.getModuleNames(), function ( module
) {
2755 return mw
.loader
.getState( module
) === 'loading';
2757 // We only need a callback, not any actual module. First try a single using()
2758 // for all loading modules. If one fails, fall back to tracking each module
2759 // separately via $.when(), this is expensive.
2760 loading
= mw
.loader
.using( modules
).then( null, function () {
2761 var all
= modules
.map( function ( module
) {
2762 return mw
.loader
.using( module
).then( null, function () {
2763 return $.Deferred().resolve();
2766 return $.when
.apply( $, all
);
2768 loading
.then( function () {
2769 /* global mwPerformance */
2770 mwPerformance
.mark( 'mwLoadEnd' );
2771 mw
.hook( 'resourceloader.loadEnd' ).fire();
2775 // Attach to window and globally alias
2776 window
.mw
= window
.mediaWiki
= mw
;