2 * Base library for MediaWiki.
4 * Exposed globally as `mediaWiki` with `mw` as shortcut.
7 * @alternateClassName mediaWiki
14 var mw
, StringSet
, log
,
15 hasOwn
= Object
.prototype.hasOwnProperty
,
16 slice
= Array
.prototype.slice
,
17 trackCallbacks
= $.Callbacks( 'memory' ),
22 * FNV132 hash function
24 * This function implements the 32-bit version of FNV-1.
25 * It is equivalent to hash( 'fnv132', ... ) in PHP, except
26 * its output is base 36 rather than hex.
27 * See <https://en.wikipedia.org/wiki/FNV_hash_function>
30 * @param {string} str String to hash
31 * @return {string} hash as an seven-character base 36 string
33 function fnv132( str
) {
34 /* eslint-disable no-bitwise */
35 var hash
= 0x811C9DC5,
38 for ( i
= 0; i
< str
.length
; i
++ ) {
39 hash
+= ( hash
<< 1 ) + ( hash
<< 4 ) + ( hash
<< 7 ) + ( hash
<< 8 ) + ( hash
<< 24 );
40 hash
^= str
.charCodeAt( i
);
43 hash
= ( hash
>>> 0 ).toString( 36 );
44 while ( hash
.length
< 7 ) {
49 /* eslint-enable no-bitwise */
52 function defineFallbacks() {
53 // <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set>
54 StringSet
= window
.Set
|| ( function () {
59 function StringSet() {
62 StringSet
.prototype.add = function ( value
) {
63 this.set[ value
] = true;
65 StringSet
.prototype.has = function ( value
) {
66 return hasOwn
.call( this.set, value
);
73 * Alias property to the global object.
80 * @param {Mixed} value
82 function setGlobalMapValue( map
, key
, value
) {
83 map
.values
[ key
] = value
;
88 // Deprecation notice for mw.config globals (T58550, T72470)
89 map
=== mw
.config
&& 'Use mw.config instead.'
94 * Create an object that can be read from or written to via methods that allow
95 * interaction both with single and multiple properties at once.
101 * @param {boolean} [global=false] Whether to synchronise =values to the global
102 * window object (for backwards-compatibility with mw.config; T72470). Values are
103 * copied in one direction only. Changes to globals do not reflect in the map.
105 function Map( global
) {
107 if ( global
=== true ) {
108 // Override #set to also set the global variable
109 this.set = function ( selection
, value
) {
111 if ( arguments
.length
> 1 ) {
112 if ( typeof selection
!== 'string' ) {
115 setGlobalMapValue( this, selection
, value
);
118 if ( typeof selection
=== 'object' ) {
119 for ( s
in selection
) {
120 setGlobalMapValue( this, s
, selection
[ s
] );
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
) {
186 // Use `arguments.length` because `undefined` is also a valid value.
187 if ( arguments
.length
> 1 ) {
188 if ( typeof selection
!== 'string' ) {
191 this.values
[ selection
] = value
;
194 if ( typeof selection
=== 'object' ) {
195 for ( s
in selection
) {
196 this.values
[ s
] = selection
[ s
];
204 * Check if one or more keys exist.
206 * @param {Mixed} selection Key or array of keys to check
207 * @return {boolean} True if the key(s) exist
209 exists: function ( selection
) {
211 if ( Array
.isArray( selection
) ) {
212 for ( i
= 0; i
< selection
.length
; i
++ ) {
213 if ( typeof selection
[ i
] !== 'string' || !hasOwn
.call( this.values
, selection
[ i
] ) ) {
219 return typeof selection
=== 'string' && hasOwn
.call( this.values
, selection
);
224 * Object constructor for messages.
226 * Similar to the Message class in MediaWiki PHP.
228 * Format defaults to 'text'.
234 * 'hello': 'Hello world',
235 * 'hello-user': 'Hello, $1!',
236 * 'welcome-user': 'Welcome back to $2, $1! Last visit by $1: $3'
239 * obj = new mw.Message( mw.messages, 'hello' );
240 * mw.log( obj.text() );
243 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John Doe' ] );
244 * mw.log( obj.text() );
245 * // Hello, John Doe!
247 * obj = new mw.Message( mw.messages, 'welcome-user', [ 'John Doe', 'Wikipedia', '2 hours ago' ] );
248 * mw.log( obj.text() );
249 * // Welcome back to Wikipedia, John Doe! Last visit by John Doe: 2 hours ago
251 * // Using mw.message shortcut
252 * obj = mw.message( 'hello-user', 'John Doe' );
253 * mw.log( obj.text() );
254 * // Hello, John Doe!
256 * // Using mw.msg shortcut
257 * str = mw.msg( 'hello-user', 'John Doe' );
259 * // Hello, John Doe!
261 * // Different formats
262 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John "Wiki" <3 Doe' ] );
264 * obj.format = 'text';
265 * str = obj.toString();
270 * // Hello, John "Wiki" <3 Doe!
272 * mw.log( obj.escaped() );
273 * // Hello, John "Wiki" <3 Doe!
278 * @param {mw.Map} map Message store
279 * @param {string} key
280 * @param {Array} [parameters]
282 function Message( map
, key
, parameters
) {
283 this.format
= 'text';
286 this.parameters
= parameters
=== undefined ? [] : slice
.call( parameters
);
290 Message
.prototype = {
292 * Get parsed contents of the message.
294 * The default parser does simple $N replacements and nothing else.
295 * This may be overridden to provide a more complex message parser.
296 * The primary override is in the mediawiki.jqueryMsg module.
298 * This function will not be called for nonexistent messages.
300 * @return {string} Parsed message
302 parser: function () {
303 return mw
.format
.apply( null, [ this.map
.get( this.key
) ].concat( this.parameters
) );
307 * Add (does not replace) parameters for `$N` placeholder values.
309 * @param {Array} parameters
310 * @return {mw.Message}
313 params: function ( parameters
) {
315 for ( i
= 0; i
< parameters
.length
; i
++ ) {
316 this.parameters
.push( parameters
[ i
] );
322 * Convert message object to its string form based on current format.
324 * @return {string} Message as a string in the current form, or `<key>` if key
327 toString: function () {
330 if ( !this.exists() ) {
331 // Use ⧼key⧽ as text if key does not exist
332 // Err on the side of safety, ensure that the output
333 // is always html safe in the event the message key is
334 // missing, since in that case its highly likely the
335 // message key is user-controlled.
336 // '⧼' is used instead of '<' to side-step any
337 // double-escaping issues.
338 // (Keep synchronised with Message::toString() in PHP.)
339 return '⧼' + mw
.html
.escape( this.key
) + '⧽';
342 if ( this.format
=== 'plain' || this.format
=== 'text' || this.format
=== 'parse' ) {
343 text
= this.parser();
346 if ( this.format
=== 'escaped' ) {
347 text
= this.parser();
348 text
= mw
.html
.escape( text
);
355 * Change format to 'parse' and convert message to string
357 * If jqueryMsg is loaded, this parses the message text from wikitext
358 * (where supported) to HTML
360 * Otherwise, it is equivalent to plain.
362 * @return {string} String form of parsed message
365 this.format
= 'parse';
366 return this.toString();
370 * Change format to 'plain' and convert message to string
372 * This substitutes parameters, but otherwise does not change the
375 * @return {string} String form of plain message
378 this.format
= 'plain';
379 return this.toString();
383 * Change format to 'text' and convert message to string
385 * If jqueryMsg is loaded, {{-transformation is done where supported
386 * (such as {{plural:}}, {{gender:}}, {{int:}}).
388 * Otherwise, it is equivalent to plain
390 * @return {string} String form of text message
393 this.format
= 'text';
394 return this.toString();
398 * Change the format to 'escaped' and convert message to string
400 * This is equivalent to using the 'text' format (see #text), then
401 * HTML-escaping the output.
403 * @return {string} String form of html escaped message
405 escaped: function () {
406 this.format
= 'escaped';
407 return this.toString();
411 * Check if a message exists
416 exists: function () {
417 return this.map
.exists( this.key
);
423 /* eslint-disable no-console */
424 log
= ( function () {
426 * Write a verbose message to the browser's console in debug mode.
428 * This method is mainly intended for verbose logging. It is a no-op in production mode.
429 * In ResourceLoader debug mode, it will use the browser's console if available, with
430 * fallback to creating a console interface in the DOM and logging messages there.
432 * See {@link mw.log} for other logging methods.
435 * @param {...string} msg Messages to output to console.
437 var log = function () {},
438 console
= window
.console
;
440 // Note: Keep list of methods in sync with restoration in mediawiki.log.js
441 // when adding or removing mw.log methods below!
444 * Collection of methods to help log messages to the console.
451 * Write a message to the browser console's warning channel.
453 * This method is a no-op in browsers that don't implement the Console API.
455 * @param {...string} msg Messages to output to console
457 log
.warn
= console
&& console
.warn
&& Function
.prototype.bind
?
458 Function
.prototype.bind
.call( console
.warn
, console
) :
462 * Write a message to the browser console's error channel.
464 * Most browsers also print a stacktrace when calling this method if the
465 * argument is an Error object.
467 * This method is a no-op in browsers that don't implement the Console API.
470 * @param {Error|...string} msg Messages to output to console
472 log
.error
= console
&& console
.error
&& Function
.prototype.bind
?
473 Function
.prototype.bind
.call( console
.error
, console
) :
477 * Create a property on a host object that, when accessed, will produce
478 * a deprecation warning in the console.
480 * @param {Object} obj Host object of deprecated property
481 * @param {string} key Name of property to create in `obj`
482 * @param {Mixed} val The value this property should return when accessed
483 * @param {string} [msg] Optional text to include in the deprecation message
484 * @param {string} [logName=key] Optional custom name for the feature.
485 * This is used instead of `key` in the message and `mw.deprecate` tracking.
487 log
.deprecate
= !Object
.defineProperty
? function ( obj
, key
, val
) {
489 } : function ( obj
, key
, val
, msg
, logName
) {
490 var logged
= new StringSet();
491 logName
= logName
|| key
;
492 msg
= 'Use of "' + logName
+ '" is deprecated.' + ( msg
? ( ' ' + msg
) : '' );
493 function uniqueTrace() {
494 var trace
= new Error().stack
;
495 if ( logged
.has( trace
) ) {
501 // Support: Safari 5.0
502 // Throws "not supported on DOM Objects" for Node or Element objects (incl. document)
503 // Safari 4.0 doesn't have this method, and it was fixed in Safari 5.1.
505 Object
.defineProperty( obj
, key
, {
509 if ( uniqueTrace() ) {
510 mw
.track( 'mw.deprecate', logName
);
515 set: function ( newVal
) {
516 if ( uniqueTrace() ) {
517 mw
.track( 'mw.deprecate', logName
);
530 /* eslint-enable no-console */
536 redefineFallbacksForTest: function () {
537 if ( !window
.QUnit
) {
538 throw new Error( 'Reset not allowed outside unit tests' );
544 * Get the current time, measured in milliseconds since January 1, 1970 (UTC).
546 * On browsers that implement the Navigation Timing API, this function will produce floating-point
547 * values with microsecond precision that are guaranteed to be monotonic. On all other browsers,
548 * it will fall back to using `Date`.
550 * @return {number} Current time
553 var perf
= window
.performance
,
554 navStart
= perf
&& perf
.timing
&& perf
.timing
.navigationStart
;
555 return navStart
&& typeof perf
.now
=== 'function' ?
556 function () { return navStart
+ perf
.now(); } :
557 function () { return Date
.now(); };
561 * Format a string. Replace $1, $2 ... $N with positional arguments.
563 * Used by Message#parser().
566 * @param {string} formatString Format string
567 * @param {...Mixed} parameters Values for $N replacements
568 * @return {string} Formatted string
570 format: function ( formatString
) {
571 var parameters
= slice
.call( arguments
, 1 );
572 return formatString
.replace( /\$(\d+)/g, function ( str
, match
) {
573 var index
= parseInt( match
, 10 ) - 1;
574 return parameters
[ index
] !== undefined ? parameters
[ index
] : '$' + match
;
579 * Track an analytic event.
581 * This method provides a generic means for MediaWiki JavaScript code to capture state
582 * information for analysis. Each logged event specifies a string topic name that describes
583 * the kind of event that it is. Topic names consist of dot-separated path components,
584 * arranged from most general to most specific. Each path component should have a clear and
585 * well-defined purpose.
587 * Data handlers are registered via `mw.trackSubscribe`, and receive the full set of
588 * events that match their subcription, including those that fired before the handler was
591 * @param {string} topic Topic name
592 * @param {Object} [data] Data describing the event, encoded as an object
594 track: function ( topic
, data
) {
595 trackQueue
.push( { topic
: topic
, timeStamp
: mw
.now(), data
: data
} );
596 trackCallbacks
.fire( trackQueue
);
600 * Register a handler for subset of analytic events, specified by topic.
602 * Handlers will be called once for each tracked event, including any events that fired before the
603 * handler was registered; 'this' is set to a plain object with a 'timeStamp' property indicating
604 * the exact time at which the event fired, a string 'topic' property naming the event, and a
605 * 'data' property which is an object of event-specific data. The event topic and event data are
606 * also passed to the callback as the first and second arguments, respectively.
608 * @param {string} topic Handle events whose name starts with this string prefix
609 * @param {Function} callback Handler to call for each matching tracked event
610 * @param {string} callback.topic
611 * @param {Object} [callback.data]
613 trackSubscribe: function ( topic
, callback
) {
615 function handler( trackQueue
) {
617 for ( ; seen
< trackQueue
.length
; seen
++ ) {
618 event
= trackQueue
[ seen
];
619 if ( event
.topic
.indexOf( topic
) === 0 ) {
620 callback
.call( event
, event
.topic
, event
.data
);
625 trackHandlers
.push( [ handler
, callback
] );
627 trackCallbacks
.add( handler
);
631 * Stop handling events for a particular handler
633 * @param {Function} callback
635 trackUnsubscribe: function ( callback
) {
636 trackHandlers
= trackHandlers
.filter( function ( fns
) {
637 if ( fns
[ 1 ] === callback
) {
638 trackCallbacks
.remove( fns
[ 0 ] );
639 // Ensure the tuple is removed to avoid holding on to closures
646 // Expose Map constructor
649 // Expose Message constructor
653 * Map of configuration values.
655 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
658 * If `$wgLegacyJavaScriptGlobals` is true, this Map will add its values to the
659 * global `window` object.
661 * @property {mw.Map} config
663 // Dummy placeholder later assigned in ResourceLoaderStartUpModule
667 * Empty object for third-party libraries, for cases where you don't
668 * want to add a new global, or the global is bad and needs containment
676 * Access container for deprecated functionality that can be moved from
677 * from their legacy location and attached to this object (e.g. a global
678 * function that is deprecated and as stop-gap can be exposed through here).
680 * This was reserved for future use but never ended up being used.
682 * @deprecated since 1.22 Let deprecated identifiers keep their original name
683 * and use mw.log#deprecate to create an access container for tracking.
689 * Store for messages.
696 * Store for templates associated with a module.
700 templates
: new Map(),
703 * Get a message object.
705 * Shortcut for `new mw.Message( mw.messages, key, parameters )`.
708 * @param {string} key Key of message to get
709 * @param {...Mixed} parameters Values for $N replacements
710 * @return {mw.Message}
712 message: function ( key
) {
713 var parameters
= slice
.call( arguments
, 1 );
714 return new Message( mw
.messages
, key
, parameters
);
718 * Get a message string using the (default) 'text' format.
720 * Shortcut for `mw.message( key, parameters... ).text()`.
723 * @param {string} key Key of message to get
724 * @param {...Mixed} parameters Values for $N replacements
728 return mw
.message
.apply( mw
.message
, arguments
).toString();
735 * Client for ResourceLoader server end point.
737 * This client is in charge of maintaining the module registry and state
738 * machine, initiating network (batch) requests for loading modules, as
739 * well as dependency resolution and execution of source code.
741 * For more information, refer to
742 * <https://www.mediawiki.org/wiki/ResourceLoader/Features>
747 loader
: ( function () {
750 * Fired via mw.track on various resource loading errors.
752 * @event resourceloader_exception
753 * @param {Error|Mixed} e The error that was thrown. Almost always an Error
754 * object, but in theory module code could manually throw something else, and that
755 * might also end up here.
756 * @param {string} [module] Name of the module which caused the error. Omitted if the
757 * error is not module-related or the module cannot be easily identified due to
759 * @param {string} source Source of the error. Possible values:
761 * - style: stylesheet error (only affects old IE where a special style loading method
763 * - load-callback: exception thrown by user callback
764 * - module-execute: exception thrown by module code
765 * - resolve: failed to sort dependencies for a module in mw.loader.load
766 * - store-eval: could not evaluate module code cached in localStorage
767 * - store-localstorage-init: localStorage or JSON parse error in mw.loader.store.init
768 * - store-localstorage-json: JSON conversion error in mw.loader.store.set
769 * - store-localstorage-update: localStorage or JSON conversion error in mw.loader.store.update
773 * Fired via mw.track on resource loading error conditions.
775 * @event resourceloader_assert
776 * @param {string} source Source of the error. Possible values:
778 * - bug-T59567: failed to cache script due to an Opera function -> string conversion
779 * bug; see <https://phabricator.wikimedia.org/T59567> for details
783 * Mapping of registered modules.
785 * See #implement and #execute for exact details on support for script, style and messages.
791 * // From mw.loader.register()
792 * 'version': '########' (hash)
793 * 'dependencies': ['required.foo', 'bar.also', ...]
794 * 'group': 'somegroup', (or) null
795 * 'source': 'local', (or) 'anotherwiki'
796 * 'skip': 'return !!window.Example', (or) null
797 * 'module': export Object
799 * // Set from execute() or mw.loader.state()
800 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error', or 'missing'
802 * // Optionally added at run-time by mw.loader.implement()
804 * 'script': closure, array of urls, or string
805 * 'style': { ... } (see #execute)
806 * 'messages': { 'key': 'value', ... }
813 * The module is known to the system but not yet required.
814 * Meta data is registered via mw.loader#register. Calls to that method are
815 * generated server-side by the startup module.
817 * The module was required through mw.loader (either directly or as dependency of
818 * another module). The client will fetch module contents from the server.
819 * The contents are then stashed in the registry via mw.loader#implement.
821 * The module has been loaded from the server and stashed via mw.loader#implement.
822 * If the module has no more dependencies in-flight, the module will be executed
823 * immediately. Otherwise execution is deferred, controlled via #handlePending.
825 * The module is being executed.
827 * The module has been successfully executed.
829 * The module (or one of its dependencies) produced an error during execution.
831 * The module was registered client-side and requested, but the server denied knowledge
832 * of the module's existence.
838 // Mapping of sources, keyed by source-id, values are strings.
843 // 'sourceId': 'http://example.org/w/load.php'
848 // For queueModuleScript()
849 handlingPendingRequests
= false,
850 pendingRequests
= [],
852 // List of modules to be loaded
856 * List of callback jobs waiting for modules to be ready.
858 * Jobs are created by #enqueue() and run by #handlePending().
860 * Typically when a job is created for a module, the job's dependencies contain
861 * both the required module and all its recursive dependencies.
866 * 'dependencies': [ module names ],
867 * 'ready': Function callback
868 * 'error': Function callback
871 * @property {Object[]} jobs
877 * For #addEmbeddedCSS() and #addLink()
880 * @property {HTMLElement|null} marker
882 marker
= document
.querySelector( 'meta[name="ResourceLoaderDynamicStyles"]' ),
884 // For addEmbeddedCSS()
886 cssBufferTimer
= null,
888 rAF
= window
.requestAnimationFrame
|| setTimeout
;
891 * Create a new style element and add it to the DOM.
894 * @param {string} text CSS text
895 * @param {Node|null} [nextNode] The element where the style tag
896 * should be inserted before
897 * @return {HTMLElement} Reference to the created style element
899 function newStyleTag( text
, nextNode
) {
900 var el
= document
.createElement( 'style' );
901 el
.appendChild( document
.createTextNode( text
) );
902 if ( nextNode
&& nextNode
.parentNode
) {
903 nextNode
.parentNode
.insertBefore( el
, nextNode
);
905 document
.head
.appendChild( el
);
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() {
924 oldCallbacks
= cssCallbacks
;
925 // Reset cssCallbacks variable so it's not polluted by any calls to
926 // addEmbeddedCSS() from one of the callbacks (T105973)
928 for ( i
= 0; i
< oldCallbacks
.length
; i
++ ) {
934 cssCallbacks
.push( callback
);
937 // Yield once before creating the <style> tag. This lets multiple stylesheets
938 // accumulate into one buffer, allowing us to reduce how often new stylesheets
939 // are inserted in the browser. Appending a stylesheet and waiting for the
940 // browser to repaint is fairly expensive. (T47810)
942 // Don't extend the buffer if the item needs its own stylesheet.
943 // Keywords like `@import` are only valid at the start of a stylesheet (T37562).
944 if ( !cssBuffer
|| cssText
.slice( 0, '@import'.length
) !== '@import' ) {
945 // Linebreak for somewhat distinguishable sections
946 cssBuffer
+= '\n' + cssText
;
947 if ( !cssBufferTimer
) {
948 cssBufferTimer
= rAF( function () {
949 // Wrap in anonymous function that takes no arguments
950 // Support: Firefox < 13
951 // Firefox 12 has non-standard behaviour of passing a number
952 // as first argument to a setTimeout callback.
953 // http://benalman.com/news/2009/07/the-mysterious-firefox-settime/
960 // This is a scheduled flush for the buffer
962 cssBufferTimer
= null;
967 newStyleTag( cssText
, marker
);
974 * @param {Array} modules List of module names
975 * @return {string} Hash of concatenated version hashes.
977 function getCombinedVersion( modules
) {
978 var hashes
= modules
.map( function ( module
) {
979 return registry
[ module
].version
;
981 return fnv132( hashes
.join( '' ) );
985 * Determine whether all dependencies are in state 'ready', which means we may
986 * execute the module or job now.
989 * @param {Array} modules Names of modules to be checked
990 * @return {boolean} True if all modules are in state 'ready', false otherwise
992 function allReady( modules
) {
994 for ( i
= 0; i
< modules
.length
; i
++ ) {
995 if ( mw
.loader
.getState( modules
[ i
] ) !== 'ready' ) {
1003 * Determine whether all dependencies are in state 'ready', which means we may
1004 * execute the module or job now.
1007 * @param {Array} modules Names of modules to be checked
1008 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
1010 function anyFailed( modules
) {
1012 for ( i
= 0; i
< modules
.length
; i
++ ) {
1013 state
= mw
.loader
.getState( modules
[ i
] );
1014 if ( state
=== 'error' || state
=== 'missing' ) {
1022 * A module has entered state 'ready', 'error', or 'missing'. Automatically update
1023 * pending jobs and modules that depend upon this module. If the given module failed,
1024 * propagate the 'error' state up the dependency tree. Otherwise, go ahead and execute
1025 * all jobs/modules now having their dependencies satisfied.
1027 * Jobs that depend on a failed module, will have their error callback ran (if any).
1030 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
1032 function handlePending( module
) {
1033 var j
, job
, hasErrors
, m
, stateChange
;
1035 if ( registry
[ module
].state
=== 'error' || registry
[ module
].state
=== 'missing' ) {
1036 // If the current module failed, mark all dependent modules also as failed.
1037 // Iterate until steady-state to propagate the error state upwards in the
1040 stateChange
= false;
1041 for ( m
in registry
) {
1042 if ( registry
[ m
].state
!== 'error' && registry
[ m
].state
!== 'missing' ) {
1043 if ( anyFailed( registry
[ m
].dependencies
) ) {
1044 registry
[ m
].state
= 'error';
1049 } while ( stateChange
);
1052 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
1053 for ( j
= 0; j
< jobs
.length
; j
++ ) {
1054 hasErrors
= anyFailed( jobs
[ j
].dependencies
);
1055 if ( hasErrors
|| allReady( jobs
[ j
].dependencies
) ) {
1056 // All dependencies satisfied, or some have errors
1058 jobs
.splice( j
, 1 );
1062 if ( typeof job
.error
=== 'function' ) {
1063 job
.error( new Error( 'Module ' + module
+ ' has failed dependencies' ), [ module
] );
1066 if ( typeof job
.ready
=== 'function' ) {
1071 // A user-defined callback raised an exception.
1072 // Swallow it to protect our state machine!
1073 mw
.track( 'resourceloader.exception', { exception
: e
, module
: module
, source
: 'load-callback' } );
1078 if ( registry
[ module
].state
=== 'ready' ) {
1079 // The current module became 'ready'. Set it in the module store, and recursively execute all
1080 // dependent modules that are loaded and now have all dependencies satisfied.
1081 mw
.loader
.store
.set( module
, registry
[ module
] );
1082 for ( m
in registry
) {
1083 if ( registry
[ m
].state
=== 'loaded' && allReady( registry
[ m
].dependencies
) ) {
1084 // eslint-disable-next-line no-use-before-define
1092 * Resolve dependencies and detect circular references.
1095 * @param {string} module Name of the top-level module whose dependencies shall be
1096 * resolved and sorted.
1097 * @param {Array} resolved Returns a topological sort of the given module and its
1098 * dependencies, such that later modules depend on earlier modules. The array
1099 * contains the module names. If the array contains already some module names,
1100 * this function appends its result to the pre-existing array.
1101 * @param {StringSet} [unresolved] Used to track the current dependency
1102 * chain, and to report loops in the dependency graph.
1103 * @throws {Error} If any unregistered module or a dependency loop is encountered
1105 function sortDependencies( module
, resolved
, unresolved
) {
1108 if ( !hasOwn
.call( registry
, module
) ) {
1109 throw new Error( 'Unknown dependency: ' + module
);
1112 if ( registry
[ module
].skip
!== null ) {
1113 // eslint-disable-next-line no-new-func
1114 skip
= new Function( registry
[ module
].skip
);
1115 registry
[ module
].skip
= null;
1117 registry
[ module
].skipped
= true;
1118 registry
[ module
].dependencies
= [];
1119 registry
[ module
].state
= 'ready';
1120 handlePending( module
);
1125 if ( resolved
.indexOf( module
) !== -1 ) {
1126 // Module already resolved; nothing to do
1129 // Create unresolved if not passed in
1130 if ( !unresolved
) {
1131 unresolved
= new StringSet();
1133 // Tracks down dependencies
1134 deps
= registry
[ module
].dependencies
;
1135 for ( i
= 0; i
< deps
.length
; i
++ ) {
1136 if ( resolved
.indexOf( deps
[ i
] ) === -1 ) {
1137 if ( unresolved
.has( deps
[ i
] ) ) {
1138 throw new Error( mw
.format(
1139 'Circular reference detected: $1 -> $2',
1145 unresolved
.add( module
);
1146 sortDependencies( deps
[ i
], resolved
, unresolved
);
1149 resolved
.push( module
);
1153 * Get names of module that a module depends on, in their proper dependency order.
1156 * @param {string[]} modules Array of string module names
1157 * @return {Array} List of dependencies, including 'module'.
1158 * @throws {Error} If an unregistered module or a dependency loop is encountered
1160 function resolve( modules
) {
1161 var i
, resolved
= [];
1162 for ( i
= 0; i
< modules
.length
; i
++ ) {
1163 sortDependencies( modules
[ i
], resolved
);
1169 * Like #resolve(), except it will silently ignore modules that
1170 * are missing or have missing dependencies.
1173 * @param {string[]} modules Array of string module names
1174 * @return {Array} List of dependencies.
1176 function resolveStubbornly( modules
) {
1177 var i
, saved
, resolved
= [];
1178 for ( i
= 0; i
< modules
.length
; i
++ ) {
1179 saved
= resolved
.slice();
1181 sortDependencies( modules
[ i
], resolved
);
1183 // This module is unknown or has unknown dependencies.
1184 // Undo any incomplete resolutions made and keep going.
1186 mw
.track( 'resourceloader.exception', {
1196 * Load and execute a script.
1199 * @param {string} src URL to script, will be used as the src attribute in the script tag
1200 * @param {Function} [callback] Callback to run after request resolution
1202 function addScript( src
, callback
) {
1203 var script
= document
.createElement( 'script' );
1205 script
.onload
= script
.onerror = function () {
1206 if ( script
.parentNode
) {
1207 script
.parentNode
.removeChild( script
);
1215 document
.head
.appendChild( script
);
1219 * Queue the loading and execution of a script for a particular module.
1222 * @param {string} src URL of the script
1223 * @param {string} moduleName Name of currently executing module
1224 * @param {Function} callback Callback to run after addScript() resolution
1226 function queueModuleScript( src
, moduleName
, callback
) {
1227 pendingRequests
.push( function () {
1228 if ( hasOwn
.call( registry
, moduleName
) ) {
1229 // Emulate runScript() part of execute()
1230 window
.require
= mw
.loader
.require
;
1231 window
.module
= registry
[ moduleName
].module
;
1233 addScript( src
, function () {
1234 // 'module.exports' should not persist after the file is executed to
1235 // avoid leakage to unrelated code. 'require' should be kept, however,
1236 // as asynchronous access to 'require' is allowed and expected. (T144879)
1237 delete window
.module
;
1239 // Start the next one (if any)
1240 if ( pendingRequests
[ 0 ] ) {
1241 pendingRequests
.shift()();
1243 handlingPendingRequests
= false;
1247 if ( !handlingPendingRequests
&& pendingRequests
[ 0 ] ) {
1248 handlingPendingRequests
= true;
1249 pendingRequests
.shift()();
1254 * Utility function for execute()
1257 * @param {string} [media] Media attribute
1258 * @param {string} url URL
1260 function addLink( media
, url
) {
1261 var el
= document
.createElement( 'link' );
1263 el
.rel
= 'stylesheet';
1264 if ( media
&& media
!== 'all' ) {
1267 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1268 // see #addEmbeddedCSS, T33676, T43331, and T49277 for details.
1271 if ( marker
&& marker
.parentNode
) {
1272 marker
.parentNode
.insertBefore( el
, marker
);
1274 document
.head
.appendChild( el
);
1280 * @param {string} code JavaScript code
1282 function domEval( code
) {
1283 var script
= document
.createElement( 'script' );
1285 document
.head
.appendChild( script
);
1286 script
.parentNode
.removeChild( script
);
1290 * Executes a loaded module, making it ready to use
1293 * @param {string} module Module name to execute
1295 function execute( module
) {
1296 var key
, value
, media
, i
, urls
, cssHandle
, checkCssHandles
, runScript
,
1297 cssHandlesRegistered
= false;
1299 if ( !hasOwn
.call( registry
, module
) ) {
1300 throw new Error( 'Module has not been registered yet: ' + module
);
1302 if ( registry
[ module
].state
!== 'loaded' ) {
1303 throw new Error( 'Module in state "' + registry
[ module
].state
+ '" may not be executed: ' + module
);
1306 registry
[ module
].state
= 'executing';
1308 runScript = function () {
1309 var script
, markModuleReady
, nestedAddScript
;
1311 script
= registry
[ module
].script
;
1312 markModuleReady = function () {
1313 registry
[ module
].state
= 'ready';
1314 handlePending( module
);
1316 nestedAddScript = function ( arr
, callback
, i
) {
1317 // Recursively call queueModuleScript() in its own callback
1318 // for each element of arr.
1319 if ( i
>= arr
.length
) {
1320 // We're at the end of the array
1325 queueModuleScript( arr
[ i
], module
, function () {
1326 nestedAddScript( arr
, callback
, i
+ 1 );
1331 if ( Array
.isArray( script
) ) {
1332 nestedAddScript( script
, markModuleReady
, 0 );
1333 } else if ( typeof script
=== 'function' ) {
1334 // Pass jQuery twice so that the signature of the closure which wraps
1335 // the script can bind both '$' and 'jQuery'.
1336 script( $, $, mw
.loader
.require
, registry
[ module
].module
);
1339 } else if ( typeof script
=== 'string' ) {
1340 // Site and user modules are legacy scripts that run in the global scope.
1341 // This is transported as a string instead of a function to avoid needing
1342 // to use string manipulation to undo the function wrapper.
1347 // Module without script
1351 // Use mw.track instead of mw.log because these errors are common in production mode
1352 // (e.g. undefined variable), and mw.log is only enabled in debug mode.
1353 registry
[ module
].state
= 'error';
1354 mw
.track( 'resourceloader.exception', { exception
: e
, module
: module
, source
: 'module-execute' } );
1355 handlePending( module
);
1359 // Add localizations to message system
1360 if ( registry
[ module
].messages
) {
1361 mw
.messages
.set( registry
[ module
].messages
);
1364 // Initialise templates
1365 if ( registry
[ module
].templates
) {
1366 mw
.templates
.set( module
, registry
[ module
].templates
);
1369 // Make sure we don't run the scripts until all stylesheet insertions have completed.
1372 checkCssHandles = function () {
1373 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
1374 // one of the cssHandles is fired while we're still creating more handles.
1375 if ( cssHandlesRegistered
&& pending
=== 0 && runScript
) {
1376 if ( module
=== 'user' ) {
1377 // Implicit dependency on the site module. Not real dependency because
1378 // it should run after 'site' regardless of whether it succeeds or fails.
1379 mw
.loader
.using( [ 'site' ] ).always( runScript
);
1383 runScript
= undefined; // Revoke
1386 cssHandle = function () {
1387 var check
= checkCssHandles
;
1389 return function () {
1393 check
= undefined; // Revoke
1399 // Process styles (see also mw.loader.implement)
1400 // * back-compat: { <media>: css }
1401 // * back-compat: { <media>: [url, ..] }
1402 // * { "css": [css, ..] }
1403 // * { "url": { <media>: [url, ..] } }
1404 if ( registry
[ module
].style
) {
1405 for ( key
in registry
[ module
].style
) {
1406 value
= registry
[ module
].style
[ key
];
1409 if ( key
!== 'url' && key
!== 'css' ) {
1410 // Backwards compatibility, key is a media-type
1411 if ( typeof value
=== 'string' ) {
1412 // back-compat: { <media>: css }
1413 // Ignore 'media' because it isn't supported (nor was it used).
1414 // Strings are pre-wrapped in "@media". The media-type was just ""
1415 // (because it had to be set to something).
1416 // This is one of the reasons why this format is no longer used.
1417 addEmbeddedCSS( value
, cssHandle() );
1419 // back-compat: { <media>: [url, ..] }
1425 // Array of css strings in key 'css',
1426 // or back-compat array of urls from media-type
1427 if ( Array
.isArray( value
) ) {
1428 for ( i
= 0; i
< value
.length
; i
++ ) {
1429 if ( key
=== 'bc-url' ) {
1430 // back-compat: { <media>: [url, ..] }
1431 addLink( media
, value
[ i
] );
1432 } else if ( key
=== 'css' ) {
1433 // { "css": [css, ..] }
1434 addEmbeddedCSS( value
[ i
], cssHandle() );
1437 // Not an array, but a regular object
1438 // Array of urls inside media-type key
1439 } else if ( typeof value
=== 'object' ) {
1440 // { "url": { <media>: [url, ..] } }
1441 for ( media
in value
) {
1442 urls
= value
[ media
];
1443 for ( i
= 0; i
< urls
.length
; i
++ ) {
1444 addLink( media
, urls
[ i
] );
1452 cssHandlesRegistered
= true;
1457 * Add one or more modules to the module load queue.
1462 * @param {string|string[]} dependencies Module name or array of string module names
1463 * @param {Function} [ready] Callback to execute when all dependencies are ready
1464 * @param {Function} [error] Callback to execute when any dependency fails
1466 function enqueue( dependencies
, ready
, error
) {
1467 // Allow calling by single module name
1468 if ( typeof dependencies
=== 'string' ) {
1469 dependencies
= [ dependencies
];
1472 // Add ready and error callbacks if they were given
1473 if ( ready
!== undefined || error
!== undefined ) {
1475 // Narrow down the list to modules that are worth waiting for
1476 dependencies
: dependencies
.filter( function ( module
) {
1477 var state
= mw
.loader
.getState( module
);
1478 return state
=== 'registered' || state
=== 'loaded' || state
=== 'loading' || state
=== 'executing';
1485 dependencies
.forEach( function ( module
) {
1486 var state
= mw
.loader
.getState( module
);
1487 // Only queue modules that are still in the initial 'registered' state
1488 // (not ones already loading, ready or error).
1489 if ( state
=== 'registered' && queue
.indexOf( module
) === -1 ) {
1490 // Private modules must be embedded in the page. Don't bother queuing
1491 // these as the server will deny them anyway (T101806).
1492 if ( registry
[ module
].group
=== 'private' ) {
1493 registry
[ module
].state
= 'error';
1494 handlePending( module
);
1497 queue
.push( module
);
1504 function sortQuery( o
) {
1513 for ( key
= 0; key
< a
.length
; key
++ ) {
1514 sorted
[ a
[ key
] ] = o
[ a
[ key
] ];
1520 * Converts a module map of the form `{ foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }`
1521 * to a query string of the form `foo.bar,baz|bar.baz,quux`.
1523 * See `ResourceLoader::makePackedModulesString()` in PHP, of which this is a port.
1524 * On the server, unpacking is done by `ResourceLoaderContext::expandModuleNames()`.
1526 * Note: This is only half of the logic, the other half has to be in #batchRequest(),
1527 * because its implementation needs to keep track of potential string size in order
1528 * to decide when to split the requests due to url size.
1531 * @param {Object} moduleMap Module map
1533 * @return {string} return.str Module query string
1534 * @return {Array} return.list List of module names in matching order
1536 function buildModulesString( moduleMap
) {
1541 function restore( suffix
) {
1545 for ( prefix
in moduleMap
) {
1546 p
= prefix
=== '' ? '' : prefix
+ '.';
1547 str
.push( p
+ moduleMap
[ prefix
].join( ',' ) );
1548 list
.push
.apply( list
, moduleMap
[ prefix
].map( restore
) );
1551 str
: str
.join( '|' ),
1557 * Resolve indexed dependencies.
1559 * ResourceLoader uses an optimization to save space which replaces module names in
1560 * dependency lists with the index of that module within the array of module
1561 * registration data if it exists. The benefit is a significant reduction in the data
1562 * size of the startup module. This function changes those dependency lists back to
1563 * arrays of strings.
1566 * @param {Array} modules Modules array
1568 function resolveIndexedDependencies( modules
) {
1570 function resolveIndex( dep
) {
1571 return typeof dep
=== 'number' ? modules
[ dep
][ 0 ] : dep
;
1573 for ( i
= 0; i
< modules
.length
; i
++ ) {
1574 deps
= modules
[ i
][ 2 ];
1576 for ( j
= 0; j
< deps
.length
; j
++ ) {
1577 deps
[ j
] = resolveIndex( deps
[ j
] );
1585 * @param {Object} params Map of parameter names to values
1588 function makeQueryString( params
) {
1589 return Object
.keys( params
).map( function ( key
) {
1590 return encodeURIComponent( key
) + '=' + encodeURIComponent( params
[ key
] );
1595 * Create network requests for a batch of modules.
1597 * This is an internal method for #work(). This must not be called directly
1598 * unless the modules are already registered, and no request is in progress,
1599 * and the module state has already been set to `loading`.
1602 * @param {string[]} batch
1604 function batchRequest( batch
) {
1605 var reqBase
, splits
, maxQueryLength
, b
, bSource
, bGroup
, bSourceGroup
,
1606 source
, group
, i
, modules
, sourceLoadScript
,
1607 currReqBase
, currReqBaseLength
, moduleMap
, currReqModules
, l
,
1608 lastDotIndex
, prefix
, suffix
, bytesAdded
;
1611 * Start the currently drafted request to the server.
1615 function doRequest() {
1616 // Optimisation: Inherit (Object.create), not copy ($.extend)
1617 var query
= Object
.create( currReqBase
),
1618 packed
= buildModulesString( moduleMap
);
1619 query
.modules
= packed
.str
;
1620 // The packing logic can change the effective order, even if the input was
1621 // sorted. As such, the call to getCombinedVersion() must use this
1622 // effective order, instead of currReqModules, as otherwise the combined
1623 // version will not match the hash expected by the server based on
1624 // combining versions from the module query string in-order. (T188076)
1625 query
.version
= getCombinedVersion( packed
.list
);
1626 query
= sortQuery( query
);
1627 addScript( sourceLoadScript
+ '?' + makeQueryString( query
) );
1630 if ( !batch
.length
) {
1634 // Always order modules alphabetically to help reduce cache
1635 // misses for otherwise identical content.
1638 // Query parameters common to all requests
1640 skin
: mw
.config
.get( 'skin' ),
1641 lang
: mw
.config
.get( 'wgUserLanguage' ),
1642 debug
: mw
.config
.get( 'debug' )
1644 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', 2000 );
1646 // Split module list by source and by group.
1648 for ( b
= 0; b
< batch
.length
; b
++ ) {
1649 bSource
= registry
[ batch
[ b
] ].source
;
1650 bGroup
= registry
[ batch
[ b
] ].group
;
1651 if ( !hasOwn
.call( splits
, bSource
) ) {
1652 splits
[ bSource
] = {};
1654 if ( !hasOwn
.call( splits
[ bSource
], bGroup
) ) {
1655 splits
[ bSource
][ bGroup
] = [];
1657 bSourceGroup
= splits
[ bSource
][ bGroup
];
1658 bSourceGroup
.push( batch
[ b
] );
1661 for ( source
in splits
) {
1663 sourceLoadScript
= sources
[ source
];
1665 for ( group
in splits
[ source
] ) {
1667 // Cache access to currently selected list of
1668 // modules for this group from this source.
1669 modules
= splits
[ source
][ group
];
1671 // Query parameters common to requests for this module group
1672 // Optimisation: Inherit (Object.create), not copy ($.extend)
1673 currReqBase
= Object
.create( reqBase
);
1674 // User modules require a user name in the query string.
1675 if ( group
=== 'user' && mw
.config
.get( 'wgUserName' ) !== null ) {
1676 currReqBase
.user
= mw
.config
.get( 'wgUserName' );
1679 // In addition to currReqBase, doRequest() will also add 'modules' and 'version'.
1680 // > '&modules='.length === 9
1681 // > '&version=1234567'.length === 16
1683 currReqBaseLength
= makeQueryString( currReqBase
).length
+ 25;
1685 // We may need to split up the request to honor the query string length limit,
1686 // so build it piece by piece.
1687 l
= currReqBaseLength
;
1688 moduleMap
= {}; // { prefix: [ suffixes ] }
1689 currReqModules
= [];
1691 for ( i
= 0; i
< modules
.length
; i
++ ) {
1692 // Determine how many bytes this module would add to the query string
1693 lastDotIndex
= modules
[ i
].lastIndexOf( '.' );
1694 // If lastDotIndex is -1, substr() returns an empty string
1695 prefix
= modules
[ i
].substr( 0, lastDotIndex
);
1696 suffix
= modules
[ i
].slice( lastDotIndex
+ 1 );
1697 bytesAdded
= hasOwn
.call( moduleMap
, prefix
) ?
1698 suffix
.length
+ 3 : // '%2C'.length == 3
1699 modules
[ i
].length
+ 3; // '%7C'.length == 3
1701 // If the url would become too long, create a new one, but don't create empty requests
1702 if ( maxQueryLength
> 0 && currReqModules
.length
&& l
+ bytesAdded
> maxQueryLength
) {
1703 // Dispatch what we've got...
1705 // .. and start again.
1706 l
= currReqBaseLength
;
1708 currReqModules
= [];
1710 mw
.track( 'resourceloader.splitRequest', { maxQueryLength
: maxQueryLength
} );
1712 if ( !hasOwn
.call( moduleMap
, prefix
) ) {
1713 moduleMap
[ prefix
] = [];
1716 moduleMap
[ prefix
].push( suffix
);
1717 currReqModules
.push( modules
[ i
] );
1719 // If there's anything left in moduleMap, request that too
1720 if ( currReqModules
.length
) {
1729 * @param {string[]} implementations Array containing pieces of JavaScript code in the
1730 * form of calls to mw.loader#implement().
1731 * @param {Function} cb Callback in case of failure
1732 * @param {Error} cb.err
1734 function asyncEval( implementations
, cb
) {
1735 if ( !implementations
.length
) {
1738 mw
.requestIdleCallback( function () {
1740 domEval( implementations
.join( ';' ) );
1748 * Make a versioned key for a specific module.
1751 * @param {string} module Module name
1752 * @return {string|null} Module key in format '`[name]@[version]`',
1753 * or null if the module does not exist
1755 function getModuleKey( module
) {
1756 return hasOwn
.call( registry
, module
) ?
1757 ( module
+ '@' + registry
[ module
].version
) : null;
1762 * @param {string} key Module name or '`[name]@[version]`'
1765 function splitModuleKey( key
) {
1766 var index
= key
.indexOf( '@' );
1767 if ( index
=== -1 ) {
1774 name
: key
.slice( 0, index
),
1775 version
: key
.slice( index
+ 1 )
1779 /* Public Members */
1782 * The module registry is exposed as an aid for debugging and inspecting page
1783 * state; it is not a public interface for modifying the registry.
1789 moduleRegistry
: registry
,
1792 * @inheritdoc #newStyleTag
1795 addStyleTag
: newStyleTag
,
1798 * Start loading of all queued module dependencies.
1803 var q
, batch
, implementations
, sourceModules
;
1807 // Appends a list of modules from the queue to the batch
1808 for ( q
= 0; q
< queue
.length
; q
++ ) {
1809 // Only load modules which are registered
1810 if ( hasOwn
.call( registry
, queue
[ q
] ) && registry
[ queue
[ q
] ].state
=== 'registered' ) {
1811 // Prevent duplicate entries
1812 if ( batch
.indexOf( queue
[ q
] ) === -1 ) {
1813 batch
.push( queue
[ q
] );
1814 // Mark registered modules as loading
1815 registry
[ queue
[ q
] ].state
= 'loading';
1820 // Now that the queue has been processed into a batch, clear the queue.
1821 // This MUST happen before we initiate any eval or network request. Otherwise,
1822 // it is possible for a cached script to instantly trigger the same work queue
1823 // again; all before we've cleared it causing each request to include modules
1824 // which are already loaded.
1827 if ( !batch
.length
) {
1831 mw
.loader
.store
.init();
1832 if ( mw
.loader
.store
.enabled
) {
1833 implementations
= [];
1835 batch
= batch
.filter( function ( module
) {
1836 var implementation
= mw
.loader
.store
.get( module
);
1837 if ( implementation
) {
1838 implementations
.push( implementation
);
1839 sourceModules
.push( module
);
1844 asyncEval( implementations
, function ( err
) {
1846 // Not good, the cached mw.loader.implement calls failed! This should
1847 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1848 // Depending on how corrupt the string is, it is likely that some
1849 // modules' implement() succeeded while the ones after the error will
1850 // never run and leave their modules in the 'loading' state forever.
1851 mw
.loader
.store
.stats
.failed
++;
1853 // Since this is an error not caused by an individual module but by
1854 // something that infected the implement call itself, don't take any
1855 // risks and clear everything in this cache.
1856 mw
.loader
.store
.clear();
1858 mw
.track( 'resourceloader.exception', { exception
: err
, source
: 'store-eval' } );
1859 // Re-add the failed ones that are still pending back to the batch
1860 failed
= sourceModules
.filter( function ( module
) {
1861 return registry
[ module
].state
=== 'loading';
1863 batchRequest( failed
);
1867 batchRequest( batch
);
1871 * Register a source.
1873 * The #work() method will use this information to split up requests by source.
1875 * mw.loader.addSource( 'mediawikiwiki', '//www.mediawiki.org/w/load.php' );
1877 * @param {string|Object} id Source ID, or object mapping ids to load urls
1878 * @param {string} loadUrl Url to a load.php end point
1879 * @throws {Error} If source id is already registered
1881 addSource: function ( id
, loadUrl
) {
1883 // Allow multiple additions
1884 if ( typeof id
=== 'object' ) {
1885 for ( source
in id
) {
1886 mw
.loader
.addSource( source
, id
[ source
] );
1891 if ( hasOwn
.call( sources
, id
) ) {
1892 throw new Error( 'source already registered: ' + id
);
1895 sources
[ id
] = loadUrl
;
1899 * Register a module, letting the system know about it and its properties.
1901 * The startup modules contain calls to this method.
1903 * When using multiple module registration by passing an array, dependencies that
1904 * are specified as references to modules within the array will be resolved before
1905 * the modules are registered.
1907 * @param {string|Array} module Module name or array of arrays, each containing
1908 * a list of arguments compatible with this method
1909 * @param {string|number} version Module version hash (falls backs to empty string)
1910 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1911 * @param {string|Array} dependencies One string or array of strings of module
1912 * names on which this module depends.
1913 * @param {string} [group=null] Group which the module is in
1914 * @param {string} [source='local'] Name of the source
1915 * @param {string} [skip=null] Script body of the skip function
1917 register: function ( module
, version
, dependencies
, group
, source
, skip
) {
1919 // Allow multiple registration
1920 if ( typeof module
=== 'object' ) {
1921 resolveIndexedDependencies( module
);
1922 for ( i
= 0; i
< module
.length
; i
++ ) {
1923 // module is an array of module names
1924 if ( typeof module
[ i
] === 'string' ) {
1925 mw
.loader
.register( module
[ i
] );
1926 // module is an array of arrays
1927 } else if ( typeof module
[ i
] === 'object' ) {
1928 mw
.loader
.register
.apply( mw
.loader
, module
[ i
] );
1933 if ( hasOwn
.call( registry
, module
) ) {
1934 throw new Error( 'module already registered: ' + module
);
1936 if ( typeof dependencies
=== 'string' ) {
1937 // A single module name
1938 deps
= [ dependencies
];
1939 } else if ( typeof dependencies
=== 'object' ) {
1940 // Array of module names
1941 deps
= dependencies
;
1943 // List the module as registered
1944 registry
[ module
] = {
1945 // Exposed to execute() for mw.loader.implement() closures.
1946 // Import happens via require().
1950 version
: version
!== undefined ? String( version
) : '',
1951 dependencies
: deps
|| [],
1952 group
: typeof group
=== 'string' ? group
: null,
1953 source
: typeof source
=== 'string' ? source
: 'local',
1954 state
: 'registered',
1955 skip
: typeof skip
=== 'string' ? skip
: null
1960 * Implement a module given the components that make up the module.
1962 * When #load() or #using() requests one or more modules, the server
1963 * response contain calls to this function.
1965 * @param {string} module Name of module and current module version. Formatted
1966 * as '`[name]@[version]`". This version should match the requested version
1967 * (from #batchRequest and #registry). This avoids race conditions (T117587).
1968 * For back-compat with MediaWiki 1.27 and earlier, the version may be omitted.
1969 * @param {Function|Array|string} [script] Function with module code, list of URLs
1970 * to load via `<script src>`, or string of module code for `$.globalEval()`.
1971 * @param {Object} [style] Should follow one of the following patterns:
1973 * { "css": [css, ..] }
1974 * { "url": { <media>: [url, ..] } }
1976 * And for backwards compatibility (needs to be supported forever due to caching):
1979 * { <media>: [url, ..] }
1981 * The reason css strings are not concatenated anymore is T33676. We now check
1982 * whether it's safe to extend the stylesheet.
1985 * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1986 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1988 implement: function ( module
, script
, style
, messages
, templates
) {
1989 var split
= splitModuleKey( module
),
1991 version
= split
.version
;
1992 // Automatically register module
1993 if ( !hasOwn
.call( registry
, name
) ) {
1994 mw
.loader
.register( name
);
1996 // Check for duplicate implementation
1997 if ( hasOwn
.call( registry
, name
) && registry
[ name
].script
!== undefined ) {
1998 throw new Error( 'module already implemented: ' + name
);
2001 // Without this reset, if there is a version mismatch between the
2002 // requested and received module version, then mw.loader.store would
2003 // cache the response under the requested key. Thus poisoning the cache
2004 // indefinitely with a stale value. (T117587)
2005 registry
[ name
].version
= version
;
2007 // Attach components
2008 registry
[ name
].script
= script
|| null;
2009 registry
[ name
].style
= style
|| null;
2010 registry
[ name
].messages
= messages
|| null;
2011 registry
[ name
].templates
= templates
|| null;
2012 // The module may already have been marked as erroneous
2013 if ( registry
[ name
].state
!== 'error' && registry
[ name
].state
!== 'missing' ) {
2014 registry
[ name
].state
= 'loaded';
2015 if ( allReady( registry
[ name
].dependencies
) ) {
2022 * Execute a function as soon as one or more required modules are ready.
2024 * Example of inline dependency on OOjs:
2026 * mw.loader.using( 'oojs', function () {
2027 * OO.compare( [ 1 ], [ 1 ] );
2030 * Example of inline dependency obtained via `require()`:
2032 * mw.loader.using( [ 'mediawiki.util' ], function ( require ) {
2033 * var util = require( 'mediawiki.util' );
2036 * Since MediaWiki 1.23 this also returns a promise.
2038 * Since MediaWiki 1.28 the promise is resolved with a `require` function.
2040 * @param {string|Array} dependencies Module name or array of modules names the
2041 * callback depends on to be ready before executing
2042 * @param {Function} [ready] Callback to execute when all dependencies are ready
2043 * @param {Function} [error] Callback to execute if one or more dependencies failed
2044 * @return {jQuery.Promise} With a `require` function
2046 using: function ( dependencies
, ready
, error
) {
2047 var deferred
= $.Deferred();
2049 // Allow calling with a single dependency as a string
2050 if ( typeof dependencies
=== 'string' ) {
2051 dependencies
= [ dependencies
];
2055 deferred
.done( ready
);
2058 deferred
.fail( error
);
2062 // Resolve entire dependency map
2063 dependencies
= resolve( dependencies
);
2065 return deferred
.reject( e
).promise();
2067 if ( allReady( dependencies
) ) {
2068 // Run ready immediately
2069 deferred
.resolve( mw
.loader
.require
);
2070 } else if ( anyFailed( dependencies
) ) {
2071 // Execute error immediately if any dependencies have errors
2073 new Error( 'One or more dependencies failed to load' ),
2077 // Not all dependencies are ready, add to the load queue
2078 enqueue( dependencies
, function () {
2079 deferred
.resolve( mw
.loader
.require
);
2080 }, deferred
.reject
);
2083 return deferred
.promise();
2087 * Load an external script or one or more modules.
2089 * This method takes a list of unrelated modules. Use cases:
2091 * - A web page will be composed of many different widgets. These widgets independently
2092 * queue their ResourceLoader modules (`OutputPage::addModules()`). If any of them
2093 * have problems, or are no longer known (e.g. cached HTML), the other modules
2094 * should still be loaded.
2095 * - This method is used for preloading, which must not throw. Later code that
2096 * calls #using() will handle the error.
2098 * @param {string|Array} modules Either the name of a module, array of modules,
2099 * or a URL of an external script or style
2100 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
2101 * external script or style; acceptable values are "text/css" and
2102 * "text/javascript"; if no type is provided, text/javascript is assumed.
2104 load: function ( modules
, type
) {
2107 // Allow calling with a url or single dependency as a string
2108 if ( typeof modules
=== 'string' ) {
2109 // "https://example.org/x.js", "http://example.org/x.js", "//example.org/x.js", "/x.js"
2110 if ( /^(https?:)?\/?\//.test( modules
) ) {
2111 if ( type
=== 'text/css' ) {
2112 l
= document
.createElement( 'link' );
2113 l
.rel
= 'stylesheet';
2115 document
.head
.appendChild( l
);
2118 if ( type
=== 'text/javascript' || type
=== undefined ) {
2119 addScript( modules
);
2123 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type
);
2125 // Called with single module
2126 modules
= [ modules
];
2129 // Filter out top-level modules that are unknown or failed to load before.
2130 filtered
= modules
.filter( function ( module
) {
2131 var state
= mw
.loader
.getState( module
);
2132 return state
!== 'error' && state
!== 'missing';
2134 // Resolve remaining list using the known dependency tree.
2135 // This also filters out modules with unknown dependencies. (T36853)
2136 filtered
= resolveStubbornly( filtered
);
2137 // If all modules are ready, or if any modules have errors, nothing to be done.
2138 if ( allReady( filtered
) || anyFailed( filtered
) ) {
2141 if ( filtered
.length
=== 0 ) {
2144 // Some modules are not yet ready, add to module load queue.
2145 enqueue( filtered
, undefined, undefined );
2149 * Change the state of one or more modules.
2151 * @param {string|Object} module Module name or object of module name/state pairs
2152 * @param {string} state State name
2154 state: function ( module
, state
) {
2157 if ( typeof module
=== 'object' ) {
2158 for ( m
in module
) {
2159 mw
.loader
.state( m
, module
[ m
] );
2163 if ( !hasOwn
.call( registry
, module
) ) {
2164 mw
.loader
.register( module
);
2166 registry
[ module
].state
= state
;
2167 if ( state
=== 'ready' || state
=== 'error' || state
=== 'missing' ) {
2168 // Make sure pending modules depending on this one get executed if their
2169 // dependencies are now fulfilled!
2170 handlePending( module
);
2175 * Get the version of a module.
2177 * @param {string} module Name of module
2178 * @return {string|null} The version, or null if the module (or its version) is not
2181 getVersion: function ( module
) {
2182 return hasOwn
.call( registry
, module
) ? registry
[ module
].version
: null;
2186 * Get the state of a module.
2188 * @param {string} module Name of module
2189 * @return {string|null} The state, or null if the module (or its state) is not
2192 getState: function ( module
) {
2193 return hasOwn
.call( registry
, module
) ? registry
[ module
].state
: null;
2197 * Get the names of all registered modules.
2201 getModuleNames: function () {
2202 return Object
.keys( registry
);
2206 * Get the exported value of a module.
2208 * This static method is publicly exposed for debugging purposes
2209 * only and must not be used in production code. In production code,
2210 * please use the dynamically provided `require()` function instead.
2212 * In case of lazy-loaded modules via mw.loader#using(), the returned
2213 * Promise provides the function, see #using() for examples.
2217 * @param {string} moduleName Module name
2218 * @return {Mixed} Exported value
2220 require: function ( moduleName
) {
2221 var state
= mw
.loader
.getState( moduleName
);
2223 // Only ready modules can be required
2224 if ( state
!== 'ready' ) {
2225 // Module may've forgotten to declare a dependency
2226 throw new Error( 'Module "' + moduleName
+ '" is not loaded.' );
2229 return registry
[ moduleName
].module
.exports
;
2233 * On browsers that implement the localStorage API, the module store serves as a
2234 * smart complement to the browser cache. Unlike the browser cache, the module store
2235 * can slice a concatenated response from ResourceLoader into its constituent
2236 * modules and cache each of them separately, using each module's versioning scheme
2237 * to determine when the cache should be invalidated.
2240 * @class mw.loader.store
2243 // Whether the store is in use on this page.
2246 // Modules whose string representation exceeds 100 kB are
2247 // ineligible for storage. See bug T66721.
2248 MODULE_SIZE_MAX
: 100 * 1000,
2250 // The contents of the store, mapping '[name]@[version]' keys
2251 // to module implementations.
2255 stats
: { hits
: 0, misses
: 0, expired
: 0, failed
: 0 },
2258 * Construct a JSON-serializable object representing the content of the store.
2260 * @return {Object} Module store contents.
2262 toJSON: function () {
2263 return { items
: mw
.loader
.store
.items
, vary
: mw
.loader
.store
.getVary() };
2267 * Get the localStorage key for the entire module store. The key references
2268 * $wgDBname to prevent clashes between wikis which share a common host.
2270 * @return {string} localStorage item key
2272 getStoreKey: function () {
2273 return 'MediaWikiModuleStore:' + mw
.config
.get( 'wgDBname' );
2277 * Get a key on which to vary the module cache.
2279 * @return {string} String of concatenated vary conditions.
2281 getVary: function () {
2283 mw
.config
.get( 'skin' ),
2284 mw
.config
.get( 'wgResourceLoaderStorageVersion' ),
2285 mw
.config
.get( 'wgUserLanguage' )
2290 * Initialize the store.
2292 * Retrieves store from localStorage and (if successfully retrieved) decoding
2293 * the stored JSON value to a plain object.
2295 * The try / catch block is used for JSON & localStorage feature detection.
2296 * See the in-line documentation for Modernizr's localStorage feature detection
2297 * code for a full account of why we need a try / catch:
2298 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2303 if ( mw
.loader
.store
.enabled
!== null ) {
2309 // Disabled because localStorage quotas are tight and (in Firefox's case)
2310 // shared by multiple origins.
2311 // See T66721, and <https://bugzilla.mozilla.org/show_bug.cgi?id=1064466>.
2312 /Firefox|Opera/.test( navigator
.userAgent
) ||
2314 // Disabled by configuration.
2315 !mw
.config
.get( 'wgResourceLoaderStorageEnabled' )
2317 // Clear any previous store to free up space. (T66721)
2318 mw
.loader
.store
.clear();
2319 mw
.loader
.store
.enabled
= false;
2322 if ( mw
.config
.get( 'debug' ) ) {
2323 // Disable module store in debug mode
2324 mw
.loader
.store
.enabled
= false;
2329 raw
= localStorage
.getItem( mw
.loader
.store
.getStoreKey() );
2330 // If we get here, localStorage is available; mark enabled
2331 mw
.loader
.store
.enabled
= true;
2332 data
= JSON
.parse( raw
);
2333 if ( data
&& typeof data
.items
=== 'object' && data
.vary
=== mw
.loader
.store
.getVary() ) {
2334 mw
.loader
.store
.items
= data
.items
;
2338 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-init' } );
2341 if ( raw
=== undefined ) {
2342 // localStorage failed; disable store
2343 mw
.loader
.store
.enabled
= false;
2345 mw
.loader
.store
.update();
2350 * Retrieve a module from the store and update cache hit stats.
2352 * @param {string} module Module name
2353 * @return {string|boolean} Module implementation or false if unavailable
2355 get: function ( module
) {
2358 if ( !mw
.loader
.store
.enabled
) {
2362 key
= getModuleKey( module
);
2363 if ( key
in mw
.loader
.store
.items
) {
2364 mw
.loader
.store
.stats
.hits
++;
2365 return mw
.loader
.store
.items
[ key
];
2367 mw
.loader
.store
.stats
.misses
++;
2372 * Stringify a module and queue it for storage.
2374 * @param {string} module Module name
2375 * @param {Object} descriptor The module's descriptor as set in the registry
2376 * @return {boolean} Module was set
2378 set: function ( module
, descriptor
) {
2381 if ( !mw
.loader
.store
.enabled
) {
2385 key
= getModuleKey( module
);
2388 // Already stored a copy of this exact version
2389 key
in mw
.loader
.store
.items
||
2390 // Module failed to load
2391 descriptor
.state
!== 'ready' ||
2392 // Unversioned, private, or site-/user-specific
2393 !descriptor
.version
||
2394 descriptor
.group
=== 'private' ||
2395 descriptor
.group
=== 'user' ||
2396 // Partial descriptor
2397 // (e.g. skipped module, or style module with state=ready)
2398 [ descriptor
.script
, descriptor
.style
, descriptor
.messages
,
2399 descriptor
.templates
].indexOf( undefined ) !== -1
2407 JSON
.stringify( key
),
2408 typeof descriptor
.script
=== 'function' ?
2409 String( descriptor
.script
) :
2410 JSON
.stringify( descriptor
.script
),
2411 JSON
.stringify( descriptor
.style
),
2412 JSON
.stringify( descriptor
.messages
),
2413 JSON
.stringify( descriptor
.templates
)
2415 // Attempted workaround for a possible Opera bug (bug T59567).
2416 // This regex should never match under sane conditions.
2417 if ( /^\s*\(/.test( args
[ 1 ] ) ) {
2418 args
[ 1 ] = 'function' + args
[ 1 ];
2419 mw
.track( 'resourceloader.assert', { source
: 'bug-T59567' } );
2422 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-json' } );
2426 src
= 'mw.loader.implement(' + args
.join( ',' ) + ');';
2427 if ( src
.length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2430 mw
.loader
.store
.items
[ key
] = src
;
2431 mw
.loader
.store
.update();
2436 * Iterate through the module store, removing any item that does not correspond
2437 * (in name and version) to an item in the module registry.
2439 * @return {boolean} Store was pruned
2441 prune: function () {
2444 if ( !mw
.loader
.store
.enabled
) {
2448 for ( key
in mw
.loader
.store
.items
) {
2449 module
= key
.slice( 0, key
.indexOf( '@' ) );
2450 if ( getModuleKey( module
) !== key
) {
2451 mw
.loader
.store
.stats
.expired
++;
2452 delete mw
.loader
.store
.items
[ key
];
2453 } else if ( mw
.loader
.store
.items
[ key
].length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2454 // This value predates the enforcement of a size limit on cached modules.
2455 delete mw
.loader
.store
.items
[ key
];
2462 * Clear the entire module store right now.
2464 clear: function () {
2465 mw
.loader
.store
.items
= {};
2467 localStorage
.removeItem( mw
.loader
.store
.getStoreKey() );
2468 } catch ( ignored
) {}
2472 * Sync in-memory store back to localStorage.
2474 * This function debounces updates. When called with a flush already pending,
2475 * the call is coalesced into the pending update. The call to
2476 * localStorage.setItem will be naturally deferred until the page is quiescent.
2478 * Because localStorage is shared by all pages from the same origin, if multiple
2479 * pages are loaded with different module sets, the possibility exists that
2480 * modules saved by one page will be clobbered by another. But the impact would
2481 * be minor and the problem would be corrected by subsequent page views.
2485 update
: ( function () {
2486 var hasPendingWrite
= false;
2488 function flushWrites() {
2490 if ( !hasPendingWrite
|| !mw
.loader
.store
.enabled
) {
2494 mw
.loader
.store
.prune();
2495 key
= mw
.loader
.store
.getStoreKey();
2497 // Replacing the content of the module store might fail if the new
2498 // contents would exceed the browser's localStorage size limit. To
2499 // avoid clogging the browser with stale data, always remove the old
2500 // value before attempting to set the new one.
2501 localStorage
.removeItem( key
);
2502 data
= JSON
.stringify( mw
.loader
.store
);
2503 localStorage
.setItem( key
, data
);
2505 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-update' } );
2508 hasPendingWrite
= false;
2511 return function () {
2512 if ( !hasPendingWrite
) {
2513 hasPendingWrite
= true;
2514 mw
.requestIdleCallback( flushWrites
);
2523 * HTML construction helper functions
2530 * output = Html.element( 'div', {}, new Html.Raw(
2531 * Html.element( 'img', { src: '<' } )
2533 * mw.log( output ); // <div><img src="<"/></div>
2538 html
: ( function () {
2539 function escapeCallback( s
) {
2556 * Escape a string for HTML.
2558 * Converts special characters to HTML entities.
2560 * mw.html.escape( '< > \' & "' );
2561 * // Returns < > ' & "
2563 * @param {string} s The string to escape
2564 * @return {string} HTML
2566 escape: function ( s
) {
2567 return s
.replace( /['"<>&]/g, escapeCallback
);
2571 * Create an HTML element string, with safe escaping.
2573 * @param {string} name The tag name.
2574 * @param {Object} [attrs] An object with members mapping element names to values
2575 * @param {string|mw.html.Raw|mw.html.Cdata|null} [contents=null] The contents of the element.
2577 * - string: Text to be escaped.
2578 * - null: The element is treated as void with short closing form, e.g. `<br/>`.
2579 * - this.Raw: The raw value is directly included.
2580 * - this.Cdata: The raw value is directly included. An exception is
2581 * thrown if it contains any illegal ETAGO delimiter.
2582 * See <https://www.w3.org/TR/html401/appendix/notes.html#h-B.3.2>.
2583 * @return {string} HTML
2585 element: function ( name
, attrs
, contents
) {
2586 var v
, attrName
, s
= '<' + name
;
2589 for ( attrName
in attrs
) {
2590 v
= attrs
[ attrName
];
2591 // Convert name=true, to name=name
2595 } else if ( v
=== false ) {
2598 s
+= ' ' + attrName
+ '="' + this.escape( String( v
) ) + '"';
2601 if ( contents
=== undefined || contents
=== null ) {
2608 switch ( typeof contents
) {
2611 s
+= this.escape( contents
);
2615 // Convert to string
2616 s
+= String( contents
);
2619 if ( contents
instanceof this.Raw
) {
2620 // Raw HTML inclusion
2621 s
+= contents
.value
;
2622 } else if ( contents
instanceof this.Cdata
) {
2624 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
2625 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
2627 s
+= contents
.value
;
2629 throw new Error( 'mw.html.element: Invalid type of contents' );
2632 s
+= '</' + name
+ '>';
2637 * Wrapper object for raw HTML passed to mw.html.element().
2639 * @class mw.html.Raw
2641 * @param {string} value
2643 Raw: function ( value
) {
2648 * Wrapper object for CDATA element contents passed to mw.html.element()
2650 * @class mw.html.Cdata
2652 * @param {string} value
2654 Cdata: function ( value
) {
2660 // Skeleton user object, extended by the 'mediawiki.user' module.
2667 * @property {mw.Map}
2671 * @property {mw.Map}
2676 // OOUI widgets specific to MediaWiki
2680 * Registry and firing of events.
2682 * MediaWiki has various interface components that are extended, enhanced
2683 * or manipulated in some other way by extensions, gadgets and even
2686 * This framework helps streamlining the timing of when these other
2687 * code paths fire their plugins (instead of using document-ready,
2688 * which can and should be limited to firing only once).
2690 * Features like navigating to other wiki pages, previewing an edit
2691 * and editing itself – without a refresh – can then retrigger these
2692 * hooks accordingly to ensure everything still works as expected.
2696 * mw.hook( 'wikipage.content' ).add( fn ).remove( fn );
2697 * mw.hook( 'wikipage.content' ).fire( $content );
2699 * Handlers can be added and fired for arbitrary event names at any time. The same
2700 * event can be fired multiple times. The last run of an event is memorized
2701 * (similar to `$(document).ready` and `$.Deferred().done`).
2702 * This means if an event is fired, and a handler added afterwards, the added
2703 * function will be fired right away with the last given event data.
2705 * Like Deferreds and Promises, the mw.hook object is both detachable and chainable.
2706 * Thus allowing flexible use and optimal maintainability and authority control.
2707 * You can pass around the `add` and/or `fire` method to another piece of code
2708 * without it having to know the event name (or `mw.hook` for that matter).
2710 * var h = mw.hook( 'bar.ready' );
2711 * new mw.Foo( .. ).fetch( { callback: h.fire } );
2713 * Note: Events are documented with an underscore instead of a dot in the event
2714 * name due to jsduck not supporting dots in that position.
2718 hook
: ( function () {
2722 * Create an instance of mw.hook.
2726 * @param {string} name Name of hook.
2729 return function ( name
) {
2730 var list
= hasOwn
.call( lists
, name
) ?
2732 lists
[ name
] = $.Callbacks( 'memory' );
2736 * Register a hook handler
2738 * @param {...Function} handler Function to bind.
2744 * Unregister a hook handler
2746 * @param {...Function} handler Function to unbind.
2749 remove
: list
.remove
,
2754 * @param {...Mixed} data
2759 return list
.fireWith
.call( this, null, slice
.call( arguments
) );
2766 // Alias $j to jQuery for backwards compatibility
2767 // @deprecated since 1.23 Use $ or jQuery instead
2768 mw
.log
.deprecate( window
, '$j', $, 'Use $ or jQuery instead.' );
2771 * Log a message to window.console, if possible.
2773 * Useful to force logging of some errors that are otherwise hard to detect (i.e., this logs
2774 * also in production mode). Gets console references in each invocation instead of caching the
2775 * reference, so that debugging tools loaded later are supported (e.g. Firebug Lite in IE).
2778 * @param {string} topic Stream name passed by mw.track
2779 * @param {Object} data Data passed by mw.track
2780 * @param {Error} [data.exception]
2781 * @param {string} data.source Error source
2782 * @param {string} [data.module] Name of module which caused the error
2784 function logError( topic
, data
) {
2785 /* eslint-disable no-console */
2788 source
= data
.source
,
2789 module
= data
.module
,
2790 console
= window
.console
;
2792 if ( console
&& console
.log
) {
2793 msg
= ( e
? 'Exception' : 'Error' ) + ' in ' + source
;
2795 msg
+= ' in module ' + module
;
2797 msg
+= ( e
? ':' : '.' );
2800 // If we have an exception object, log it to the warning channel to trigger
2801 // proper stacktraces in browsers that support it.
2802 if ( e
&& console
.warn
) {
2806 /* eslint-enable no-console */
2809 // Subscribe to error streams
2810 mw
.trackSubscribe( 'resourceloader.exception', logError
);
2811 mw
.trackSubscribe( 'resourceloader.assert', logError
);
2813 // Attach to window and globally alias
2814 window
.mw
= window
.mediaWiki
= mw
;