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
,
19 * FNV132 hash function
21 * This function implements the 32-bit version of FNV-1.
22 * It is equivalent to hash( 'fnv132', ... ) in PHP, except
23 * its output is base 36 rather than hex.
24 * See <https://en.wikipedia.org/wiki/FNV_hash_function>
27 * @param {string} str String to hash
28 * @return {string} hash as an seven-character base 36 string
30 function fnv132( str
) {
31 /* eslint-disable no-bitwise */
32 var hash
= 0x811C9DC5,
35 for ( i
= 0; i
< str
.length
; i
++ ) {
36 hash
+= ( hash
<< 1 ) + ( hash
<< 4 ) + ( hash
<< 7 ) + ( hash
<< 8 ) + ( hash
<< 24 );
37 hash
^= str
.charCodeAt( i
);
40 hash
= ( hash
>>> 0 ).toString( 36 );
41 while ( hash
.length
< 7 ) {
46 /* eslint-enable no-bitwise */
49 function defineFallbacks() {
50 // <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set>
51 StringSet
= window
.Set
|| ( function () {
56 function StringSet() {
59 StringSet
.prototype.add = function ( value
) {
60 this.set[ value
] = true;
62 StringSet
.prototype.has = function ( value
) {
63 return hasOwn
.call( this.set, value
);
70 * Alias property to the global object.
77 * @param {Mixed} value
79 function setGlobalMapValue( map
, key
, value
) {
80 map
.values
[ key
] = value
;
85 // Deprecation notice for mw.config globals (T58550, T72470)
86 map
=== mw
.config
&& 'Use mw.config instead.'
91 * Log a message to window.console, if possible.
93 * Useful to force logging of some errors that are otherwise hard to detect (i.e., this logs
94 * also in production mode). Gets console references in each invocation instead of caching the
95 * reference, so that debugging tools loaded later are supported (e.g. Firebug Lite in IE).
98 * @param {string} topic Stream name passed by mw.track
99 * @param {Object} data Data passed by mw.track
100 * @param {Error} [data.exception]
101 * @param {string} data.source Error source
102 * @param {string} [data.module] Name of module which caused the error
104 function logError( topic
, data
) {
105 /* eslint-disable no-console */
108 source
= data
.source
,
109 module
= data
.module
,
110 console
= window
.console
;
112 if ( console
&& console
.log
) {
113 msg
= ( e
? 'Exception' : 'Error' ) + ' in ' + source
;
115 msg
+= ' in module ' + module
;
117 msg
+= ( e
? ':' : '.' );
120 // If we have an exception object, log it to the warning channel to trigger
121 // proper stacktraces in browsers that support it.
122 if ( e
&& console
.warn
) {
126 /* eslint-enable no-console */
130 * Create an object that can be read from or written to via methods that allow
131 * interaction both with single and multiple properties at once.
137 * @param {boolean} [global=false] Whether to synchronise =values to the global
138 * window object (for backwards-compatibility with mw.config; T72470). Values are
139 * copied in one direction only. Changes to globals do not reflect in the map.
141 function Map( global
) {
143 if ( global
=== true ) {
144 // Override #set to also set the global variable
145 this.set = function ( selection
, value
) {
147 if ( arguments
.length
> 1 ) {
148 if ( typeof selection
!== 'string' ) {
151 setGlobalMapValue( this, selection
, value
);
154 if ( typeof selection
=== 'object' ) {
155 for ( s
in selection
) {
156 setGlobalMapValue( this, s
, selection
[ s
] );
169 * Get the value of one or more keys.
171 * If called with no arguments, all values are returned.
173 * @param {string|Array} [selection] Key or array of keys to retrieve values for.
174 * @param {Mixed} [fallback=null] Value for keys that don't exist.
175 * @return {Mixed|Object|null} If selection was a string, returns the value,
176 * If selection was an array, returns an object of key/values.
177 * If no selection is passed, a new object with all key/values is returned.
179 get: function ( selection
, fallback
) {
181 fallback
= arguments
.length
> 1 ? fallback
: null;
183 if ( Array
.isArray( selection
) ) {
185 for ( i
= 0; i
< selection
.length
; i
++ ) {
186 if ( typeof selection
[ i
] === 'string' ) {
187 results
[ selection
[ i
] ] = hasOwn
.call( this.values
, selection
[ i
] ) ?
188 this.values
[ selection
[ i
] ] :
195 if ( typeof selection
=== 'string' ) {
196 return hasOwn
.call( this.values
, selection
) ?
197 this.values
[ selection
] :
201 if ( selection
=== undefined ) {
203 for ( i
in this.values
) {
204 results
[ i
] = this.values
[ i
];
209 // Invalid selection key
214 * Set one or more key/value pairs.
216 * @param {string|Object} selection Key to set value for, or object mapping keys to values
217 * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
218 * @return {boolean} True on success, false on failure
220 set: function ( selection
, value
) {
222 // Use `arguments.length` because `undefined` is also a valid value.
223 if ( arguments
.length
> 1 ) {
224 if ( typeof selection
!== 'string' ) {
227 this.values
[ selection
] = value
;
230 if ( typeof selection
=== 'object' ) {
231 for ( s
in selection
) {
232 this.values
[ s
] = selection
[ s
];
240 * Check if one or more keys exist.
242 * @param {Mixed} selection Key or array of keys to check
243 * @return {boolean} True if the key(s) exist
245 exists: function ( selection
) {
247 if ( Array
.isArray( selection
) ) {
248 for ( i
= 0; i
< selection
.length
; i
++ ) {
249 if ( typeof selection
[ i
] !== 'string' || !hasOwn
.call( this.values
, selection
[ i
] ) ) {
255 return typeof selection
=== 'string' && hasOwn
.call( this.values
, selection
);
261 /* eslint-disable no-console */
262 log
= ( function () {
264 * Write a verbose message to the browser's console in debug mode.
266 * This method is mainly intended for verbose logging. It is a no-op in production mode.
267 * In ResourceLoader debug mode, it will use the browser's console if available, with
268 * fallback to creating a console interface in the DOM and logging messages there.
270 * See {@link mw.log} for other logging methods.
273 * @param {...string} msg Messages to output to console.
275 var log = function () {},
276 console
= window
.console
;
278 // Note: Keep list of methods in sync with restoration in mediawiki.log.js
279 // when adding or removing mw.log methods below!
282 * Collection of methods to help log messages to the console.
289 * Write a message to the browser console's warning channel.
291 * This method is a no-op in browsers that don't implement the Console API.
293 * @param {...string} msg Messages to output to console
295 log
.warn
= console
&& console
.warn
&& Function
.prototype.bind
?
296 Function
.prototype.bind
.call( console
.warn
, console
) :
300 * Write a message to the browser console's error channel.
302 * Most browsers also print a stacktrace when calling this method if the
303 * argument is an Error object.
305 * This method is a no-op in browsers that don't implement the Console API.
308 * @param {...Mixed} msg Messages to output to console
310 log
.error
= console
&& console
.error
&& Function
.prototype.bind
?
311 Function
.prototype.bind
.call( console
.error
, console
) :
315 * Create a property on a host object that, when accessed, will produce
316 * a deprecation warning in the console.
318 * @param {Object} obj Host object of deprecated property
319 * @param {string} key Name of property to create in `obj`
320 * @param {Mixed} val The value this property should return when accessed
321 * @param {string} [msg] Optional text to include in the deprecation message
322 * @param {string} [logName=key] Optional custom name for the feature.
323 * This is used instead of `key` in the message and `mw.deprecate` tracking.
325 log
.deprecate
= !Object
.defineProperty
? function ( obj
, key
, val
) {
327 } : function ( obj
, key
, val
, msg
, logName
) {
328 var logged
= new StringSet();
329 logName
= logName
|| key
;
330 msg
= 'Use of "' + logName
+ '" is deprecated.' + ( msg
? ( ' ' + msg
) : '' );
331 function uniqueTrace() {
332 var trace
= new Error().stack
;
333 if ( logged
.has( trace
) ) {
339 // Support: Safari 5.0
340 // Throws "not supported on DOM Objects" for Node or Element objects (incl. document)
341 // Safari 4.0 doesn't have this method, and it was fixed in Safari 5.1.
343 Object
.defineProperty( obj
, key
, {
347 if ( uniqueTrace() ) {
348 mw
.track( 'mw.deprecate', logName
);
353 set: function ( newVal
) {
354 if ( uniqueTrace() ) {
355 mw
.track( 'mw.deprecate', logName
);
368 /* eslint-enable no-console */
374 redefineFallbacksForTest: function () {
375 if ( !window
.QUnit
) {
376 throw new Error( 'Reset not allowed outside unit tests' );
382 * Get the current time, measured in milliseconds since January 1, 1970 (UTC).
384 * On browsers that implement the Navigation Timing API, this function will produce floating-point
385 * values with microsecond precision that are guaranteed to be monotonic. On all other browsers,
386 * it will fall back to using `Date`.
388 * @return {number} Current time
391 var perf
= window
.performance
,
392 navStart
= perf
&& perf
.timing
&& perf
.timing
.navigationStart
;
393 return navStart
&& typeof perf
.now
=== 'function' ?
394 function () { return navStart
+ perf
.now(); } :
395 function () { return Date
.now(); };
399 * List of all analytic events emitted so far.
404 trackQueue
: trackQueue
,
406 track: function ( topic
, data
) {
407 trackQueue
.push( { topic
: topic
, timeStamp
: mw
.now(), data
: data
} );
408 // The base module extends this method to fire events here
412 * Track an early error event via mw.track and send it to the window console.
415 * @param {string} topic Topic name
416 * @param {Object} data Data describing the event, encoded as an object; see mw#logError
418 trackError: function ( topic
, data
) {
419 mw
.track( topic
, data
);
420 logError( topic
, data
);
423 // Expose Map constructor
427 * Map of configuration values.
429 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
432 * If `$wgLegacyJavaScriptGlobals` is true, this Map will add its values to the
433 * global `window` object.
435 * @property {mw.Map} config
437 // Dummy placeholder later assigned in ResourceLoaderStartUpModule
441 * Empty object for third-party libraries, for cases where you don't
442 * want to add a new global, or the global is bad and needs containment
450 * Access container for deprecated functionality that can be moved from
451 * from their legacy location and attached to this object (e.g. a global
452 * function that is deprecated and as stop-gap can be exposed through here).
454 * This was reserved for future use but never ended up being used.
456 * @deprecated since 1.22 Let deprecated identifiers keep their original name
457 * and use mw.log#deprecate to create an access container for tracking.
463 * Store for messages.
470 * Store for templates associated with a module.
474 templates
: new Map(),
480 * Client for ResourceLoader server end point.
482 * This client is in charge of maintaining the module registry and state
483 * machine, initiating network (batch) requests for loading modules, as
484 * well as dependency resolution and execution of source code.
486 * For more information, refer to
487 * <https://www.mediawiki.org/wiki/ResourceLoader/Features>
492 loader
: ( function () {
495 * Fired via mw.track on various resource loading errors.
497 * @event resourceloader_exception
498 * @param {Error|Mixed} e The error that was thrown. Almost always an Error
499 * object, but in theory module code could manually throw something else, and that
500 * might also end up here.
501 * @param {string} [module] Name of the module which caused the error. Omitted if the
502 * error is not module-related or the module cannot be easily identified due to
504 * @param {string} source Source of the error. Possible values:
506 * - style: stylesheet error (only affects old IE where a special style loading method
508 * - load-callback: exception thrown by user callback
509 * - module-execute: exception thrown by module code
510 * - resolve: failed to sort dependencies for a module in mw.loader.load
511 * - store-eval: could not evaluate module code cached in localStorage
512 * - store-localstorage-init: localStorage or JSON parse error in mw.loader.store.init
513 * - store-localstorage-json: JSON conversion error in mw.loader.store.set
514 * - store-localstorage-update: localStorage or JSON conversion error in mw.loader.store.update
518 * Fired via mw.track on resource loading error conditions.
520 * @event resourceloader_assert
521 * @param {string} source Source of the error. Possible values:
523 * - bug-T59567: failed to cache script due to an Opera function -> string conversion
524 * bug; see <https://phabricator.wikimedia.org/T59567> for details
528 * Mapping of registered modules.
530 * See #implement and #execute for exact details on support for script, style and messages.
536 * // From mw.loader.register()
537 * 'version': '########' (hash)
538 * 'dependencies': ['required.foo', 'bar.also', ...]
539 * 'group': 'somegroup', (or) null
540 * 'source': 'local', (or) 'anotherwiki'
541 * 'skip': 'return !!window.Example', (or) null
542 * 'module': export Object
544 * // Set from execute() or mw.loader.state()
545 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error', or 'missing'
547 * // Optionally added at run-time by mw.loader.implement()
549 * 'script': closure, array of urls, or string
550 * 'style': { ... } (see #execute)
551 * 'messages': { 'key': 'value', ... }
558 * The module is known to the system but not yet required.
559 * Meta data is registered via mw.loader#register. Calls to that method are
560 * generated server-side by the startup module.
562 * The module was required through mw.loader (either directly or as dependency of
563 * another module). The client will fetch module contents from the server.
564 * The contents are then stashed in the registry via mw.loader#implement.
566 * The module has been loaded from the server and stashed via mw.loader#implement.
567 * If the module has no more dependencies in-flight, the module will be executed
568 * immediately. Otherwise execution is deferred, controlled via #handlePending.
570 * The module is being executed.
572 * The module has been successfully executed.
574 * The module (or one of its dependencies) produced an error during execution.
576 * The module was registered client-side and requested, but the server denied knowledge
577 * of the module's existence.
583 // Mapping of sources, keyed by source-id, values are strings.
588 // 'sourceId': 'http://example.org/w/load.php'
593 // For queueModuleScript()
594 handlingPendingRequests
= false,
595 pendingRequests
= [],
597 // List of modules to be loaded
601 * List of callback jobs waiting for modules to be ready.
603 * Jobs are created by #enqueue() and run by #handlePending().
605 * Typically when a job is created for a module, the job's dependencies contain
606 * both the required module and all its recursive dependencies.
611 * 'dependencies': [ module names ],
612 * 'ready': Function callback
613 * 'error': Function callback
616 * @property {Object[]} jobs
622 * For #addEmbeddedCSS() and #addLink()
625 * @property {HTMLElement|null} marker
627 marker
= document
.querySelector( 'meta[name="ResourceLoaderDynamicStyles"]' ),
629 // For addEmbeddedCSS()
631 cssBufferTimer
= null,
633 rAF
= window
.requestAnimationFrame
|| setTimeout
;
636 * Create a new style element and add it to the DOM.
639 * @param {string} text CSS text
640 * @param {Node|null} [nextNode] The element where the style tag
641 * should be inserted before
642 * @return {HTMLElement} Reference to the created style element
644 function newStyleTag( text
, nextNode
) {
645 var el
= document
.createElement( 'style' );
646 el
.appendChild( document
.createTextNode( text
) );
647 if ( nextNode
&& nextNode
.parentNode
) {
648 nextNode
.parentNode
.insertBefore( el
, nextNode
);
650 document
.head
.appendChild( el
);
656 * Add a bit of CSS text to the current browser page.
658 * The CSS will be appended to an existing ResourceLoader-created `<style>` tag
659 * or create a new one based on whether the given `cssText` is safe for extension.
662 * @param {string} [cssText=cssBuffer] If called without cssText,
663 * the internal buffer will be inserted instead.
664 * @param {Function} [callback]
666 function addEmbeddedCSS( cssText
, callback
) {
667 function fireCallbacks() {
669 oldCallbacks
= cssCallbacks
;
670 // Reset cssCallbacks variable so it's not polluted by any calls to
671 // addEmbeddedCSS() from one of the callbacks (T105973)
673 for ( i
= 0; i
< oldCallbacks
.length
; i
++ ) {
679 cssCallbacks
.push( callback
);
682 // Yield once before creating the <style> tag. This lets multiple stylesheets
683 // accumulate into one buffer, allowing us to reduce how often new stylesheets
684 // are inserted in the browser. Appending a stylesheet and waiting for the
685 // browser to repaint is fairly expensive. (T47810)
687 // Don't extend the buffer if the item needs its own stylesheet.
688 // Keywords like `@import` are only valid at the start of a stylesheet (T37562).
689 if ( !cssBuffer
|| cssText
.slice( 0, '@import'.length
) !== '@import' ) {
690 // Linebreak for somewhat distinguishable sections
691 cssBuffer
+= '\n' + cssText
;
692 if ( !cssBufferTimer
) {
693 cssBufferTimer
= rAF( function () {
694 // Wrap in anonymous function that takes no arguments
695 // Support: Firefox < 13
696 // Firefox 12 has non-standard behaviour of passing a number
697 // as first argument to a setTimeout callback.
698 // http://benalman.com/news/2009/07/the-mysterious-firefox-settime/
705 // This is a scheduled flush for the buffer
707 cssBufferTimer
= null;
712 newStyleTag( cssText
, marker
);
719 * @param {Array} modules List of module names
720 * @return {string} Hash of concatenated version hashes.
722 function getCombinedVersion( modules
) {
723 var hashes
= modules
.map( function ( module
) {
724 return registry
[ module
].version
;
726 return fnv132( hashes
.join( '' ) );
730 * Determine whether all dependencies are in state 'ready', which means we may
731 * execute the module or job now.
734 * @param {Array} modules Names of modules to be checked
735 * @return {boolean} True if all modules are in state 'ready', false otherwise
737 function allReady( modules
) {
739 for ( i
= 0; i
< modules
.length
; i
++ ) {
740 if ( mw
.loader
.getState( modules
[ i
] ) !== 'ready' ) {
748 * Determine whether all dependencies are in state 'ready', which means we may
749 * execute the module or job now.
752 * @param {Array} modules Names of modules to be checked
753 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
755 function anyFailed( modules
) {
757 for ( i
= 0; i
< modules
.length
; i
++ ) {
758 state
= mw
.loader
.getState( modules
[ i
] );
759 if ( state
=== 'error' || state
=== 'missing' ) {
767 * A module has entered state 'ready', 'error', or 'missing'. Automatically update
768 * pending jobs and modules that depend upon this module. If the given module failed,
769 * propagate the 'error' state up the dependency tree. Otherwise, go ahead and execute
770 * all jobs/modules now having their dependencies satisfied.
772 * Jobs that depend on a failed module, will have their error callback ran (if any).
775 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
777 function handlePending( module
) {
778 var j
, job
, hasErrors
, m
, stateChange
;
780 if ( registry
[ module
].state
=== 'error' || registry
[ module
].state
=== 'missing' ) {
781 // If the current module failed, mark all dependent modules also as failed.
782 // Iterate until steady-state to propagate the error state upwards in the
786 for ( m
in registry
) {
787 if ( registry
[ m
].state
!== 'error' && registry
[ m
].state
!== 'missing' ) {
788 if ( anyFailed( registry
[ m
].dependencies
) ) {
789 registry
[ m
].state
= 'error';
794 } while ( stateChange
);
797 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
798 for ( j
= 0; j
< jobs
.length
; j
++ ) {
799 hasErrors
= anyFailed( jobs
[ j
].dependencies
);
800 if ( hasErrors
|| allReady( jobs
[ j
].dependencies
) ) {
801 // All dependencies satisfied, or some have errors
807 if ( typeof job
.error
=== 'function' ) {
808 job
.error( new Error( 'Module ' + module
+ ' has failed dependencies' ), [ module
] );
811 if ( typeof job
.ready
=== 'function' ) {
816 // A user-defined callback raised an exception.
817 // Swallow it to protect our state machine!
818 mw
.trackError( 'resourceloader.exception', {
821 source
: 'load-callback'
827 if ( registry
[ module
].state
=== 'ready' ) {
828 // The current module became 'ready'. Set it in the module store, and recursively execute all
829 // dependent modules that are loaded and now have all dependencies satisfied.
830 mw
.loader
.store
.set( module
, registry
[ module
] );
831 for ( m
in registry
) {
832 if ( registry
[ m
].state
=== 'loaded' && allReady( registry
[ m
].dependencies
) ) {
833 // eslint-disable-next-line no-use-before-define
841 * Resolve dependencies and detect circular references.
844 * @param {string} module Name of the top-level module whose dependencies shall be
845 * resolved and sorted.
846 * @param {Array} resolved Returns a topological sort of the given module and its
847 * dependencies, such that later modules depend on earlier modules. The array
848 * contains the module names. If the array contains already some module names,
849 * this function appends its result to the pre-existing array.
850 * @param {StringSet} [unresolved] Used to track the current dependency
851 * chain, and to report loops in the dependency graph.
852 * @throws {Error} If any unregistered module or a dependency loop is encountered
854 function sortDependencies( module
, resolved
, unresolved
) {
857 if ( !hasOwn
.call( registry
, module
) ) {
858 throw new Error( 'Unknown dependency: ' + module
);
861 if ( registry
[ module
].skip
!== null ) {
862 // eslint-disable-next-line no-new-func
863 skip
= new Function( registry
[ module
].skip
);
864 registry
[ module
].skip
= null;
866 registry
[ module
].skipped
= true;
867 registry
[ module
].dependencies
= [];
868 registry
[ module
].state
= 'ready';
869 handlePending( module
);
874 if ( resolved
.indexOf( module
) !== -1 ) {
875 // Module already resolved; nothing to do
878 // Create unresolved if not passed in
880 unresolved
= new StringSet();
882 // Tracks down dependencies
883 deps
= registry
[ module
].dependencies
;
884 for ( i
= 0; i
< deps
.length
; i
++ ) {
885 if ( resolved
.indexOf( deps
[ i
] ) === -1 ) {
886 if ( unresolved
.has( deps
[ i
] ) ) {
888 'Circular reference detected: ' + module
+ ' -> ' + deps
[ i
]
892 unresolved
.add( module
);
893 sortDependencies( deps
[ i
], resolved
, unresolved
);
896 resolved
.push( module
);
900 * Get names of module that a module depends on, in their proper dependency order.
903 * @param {string[]} modules Array of string module names
904 * @return {Array} List of dependencies, including 'module'.
905 * @throws {Error} If an unregistered module or a dependency loop is encountered
907 function resolve( modules
) {
908 var i
, resolved
= [];
909 for ( i
= 0; i
< modules
.length
; i
++ ) {
910 sortDependencies( modules
[ i
], resolved
);
916 * Like #resolve(), except it will silently ignore modules that
917 * are missing or have missing dependencies.
920 * @param {string[]} modules Array of string module names
921 * @return {Array} List of dependencies.
923 function resolveStubbornly( modules
) {
924 var i
, saved
, resolved
= [];
925 for ( i
= 0; i
< modules
.length
; i
++ ) {
926 saved
= resolved
.slice();
928 sortDependencies( modules
[ i
], resolved
);
930 // This module is unknown or has unknown dependencies.
931 // Undo any incomplete resolutions made and keep going.
933 mw
.trackError( 'resourceloader.exception', {
943 * Load and execute a script.
946 * @param {string} src URL to script, will be used as the src attribute in the script tag
947 * @param {Function} [callback] Callback to run after request resolution
949 function addScript( src
, callback
) {
950 var script
= document
.createElement( 'script' );
952 script
.onload
= script
.onerror = function () {
953 if ( script
.parentNode
) {
954 script
.parentNode
.removeChild( script
);
962 document
.head
.appendChild( script
);
966 * Queue the loading and execution of a script for a particular module.
969 * @param {string} src URL of the script
970 * @param {string} moduleName Name of currently executing module
971 * @param {Function} callback Callback to run after addScript() resolution
973 function queueModuleScript( src
, moduleName
, callback
) {
974 pendingRequests
.push( function () {
975 if ( hasOwn
.call( registry
, moduleName
) ) {
976 // Emulate runScript() part of execute()
977 window
.require
= mw
.loader
.require
;
978 window
.module
= registry
[ moduleName
].module
;
980 addScript( src
, function () {
981 // 'module.exports' should not persist after the file is executed to
982 // avoid leakage to unrelated code. 'require' should be kept, however,
983 // as asynchronous access to 'require' is allowed and expected. (T144879)
984 delete window
.module
;
986 // Start the next one (if any)
987 if ( pendingRequests
[ 0 ] ) {
988 pendingRequests
.shift()();
990 handlingPendingRequests
= false;
994 if ( !handlingPendingRequests
&& pendingRequests
[ 0 ] ) {
995 handlingPendingRequests
= true;
996 pendingRequests
.shift()();
1001 * Utility function for execute()
1004 * @param {string} [media] Media attribute
1005 * @param {string} url URL
1007 function addLink( media
, url
) {
1008 var el
= document
.createElement( 'link' );
1010 el
.rel
= 'stylesheet';
1011 if ( media
&& media
!== 'all' ) {
1014 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1015 // see #addEmbeddedCSS, T33676, T43331, and T49277 for details.
1018 if ( marker
&& marker
.parentNode
) {
1019 marker
.parentNode
.insertBefore( el
, marker
);
1021 document
.head
.appendChild( el
);
1027 * @param {string} code JavaScript code
1029 function domEval( code
) {
1030 var script
= document
.createElement( 'script' );
1031 if ( mw
.config
.get( 'wgCSPNonce' ) !== false ) {
1032 script
.nonce
= mw
.config
.get( 'wgCSPNonce' );
1035 document
.head
.appendChild( script
);
1036 script
.parentNode
.removeChild( script
);
1040 * Add one or more modules to the module load queue.
1045 * @param {string|string[]} dependencies Module name or array of string module names
1046 * @param {Function} [ready] Callback to execute when all dependencies are ready
1047 * @param {Function} [error] Callback to execute when any dependency fails
1049 function enqueue( dependencies
, ready
, error
) {
1050 // Allow calling by single module name
1051 if ( typeof dependencies
=== 'string' ) {
1052 dependencies
= [ dependencies
];
1055 if ( allReady( dependencies
) ) {
1056 // Run ready immediately
1057 if ( ready
!== undefined ) {
1064 if ( anyFailed( dependencies
) ) {
1065 if ( error
!== undefined ) {
1066 // Execute error immediately if any dependencies have errors
1068 new Error( 'One or more dependencies failed to load' ),
1076 // Not all dependencies are ready, add to the load queue...
1078 // Add ready and error callbacks if they were given
1079 if ( ready
!== undefined || error
!== undefined ) {
1081 // Narrow down the list to modules that are worth waiting for
1082 dependencies
: dependencies
.filter( function ( module
) {
1083 var state
= mw
.loader
.getState( module
);
1084 return state
=== 'registered' || state
=== 'loaded' || state
=== 'loading' || state
=== 'executing';
1091 dependencies
.forEach( function ( module
) {
1092 var state
= mw
.loader
.getState( module
);
1093 // Only queue modules that are still in the initial 'registered' state
1094 // (not ones already loading, ready or error).
1095 if ( state
=== 'registered' && queue
.indexOf( module
) === -1 ) {
1096 // Private modules must be embedded in the page. Don't bother queuing
1097 // these as the server will deny them anyway (T101806).
1098 if ( registry
[ module
].group
=== 'private' ) {
1099 registry
[ module
].state
= 'error';
1100 handlePending( module
);
1103 queue
.push( module
);
1111 * Executes a loaded module, making it ready to use
1114 * @param {string} module Module name to execute
1116 function execute( module
) {
1117 var key
, value
, media
, i
, urls
, cssHandle
, checkCssHandles
, runScript
,
1118 cssHandlesRegistered
= false;
1120 if ( !hasOwn
.call( registry
, module
) ) {
1121 throw new Error( 'Module has not been registered yet: ' + module
);
1123 if ( registry
[ module
].state
!== 'loaded' ) {
1124 throw new Error( 'Module in state "' + registry
[ module
].state
+ '" may not be executed: ' + module
);
1127 registry
[ module
].state
= 'executing';
1129 runScript = function () {
1130 var script
, markModuleReady
, nestedAddScript
;
1132 script
= registry
[ module
].script
;
1133 markModuleReady = function () {
1134 registry
[ module
].state
= 'ready';
1135 handlePending( module
);
1137 nestedAddScript = function ( arr
, callback
, i
) {
1138 // Recursively call queueModuleScript() in its own callback
1139 // for each element of arr.
1140 if ( i
>= arr
.length
) {
1141 // We're at the end of the array
1146 queueModuleScript( arr
[ i
], module
, function () {
1147 nestedAddScript( arr
, callback
, i
+ 1 );
1152 if ( Array
.isArray( script
) ) {
1153 nestedAddScript( script
, markModuleReady
, 0 );
1154 } else if ( typeof script
=== 'function' ) {
1155 // Pass jQuery twice so that the signature of the closure which wraps
1156 // the script can bind both '$' and 'jQuery'.
1157 script( window
.$, window
.$, mw
.loader
.require
, registry
[ module
].module
);
1160 } else if ( typeof script
=== 'string' ) {
1161 // Site and user modules are legacy scripts that run in the global scope.
1162 // This is transported as a string instead of a function to avoid needing
1163 // to use string manipulation to undo the function wrapper.
1168 // Module without script
1172 // Use mw.track instead of mw.log because these errors are common in production mode
1173 // (e.g. undefined variable), and mw.log is only enabled in debug mode.
1174 registry
[ module
].state
= 'error';
1175 mw
.trackError( 'resourceloader.exception', {
1176 exception
: e
, module
:
1177 module
, source
: 'module-execute'
1179 handlePending( module
);
1183 // Add localizations to message system
1184 if ( registry
[ module
].messages
) {
1185 mw
.messages
.set( registry
[ module
].messages
);
1188 // Initialise templates
1189 if ( registry
[ module
].templates
) {
1190 mw
.templates
.set( module
, registry
[ module
].templates
);
1193 // Make sure we don't run the scripts until all stylesheet insertions have completed.
1196 checkCssHandles = function () {
1197 var ex
, dependencies
;
1198 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
1199 // one of the cssHandles is fired while we're still creating more handles.
1200 if ( cssHandlesRegistered
&& pending
=== 0 && runScript
) {
1201 if ( module
=== 'user' ) {
1202 // Implicit dependency on the site module. Not real dependency because
1203 // it should run after 'site' regardless of whether it succeeds or fails.
1204 // Note: This is a simplified version of mw.loader.using(), inlined here
1205 // as using() depends on jQuery (T192623).
1207 dependencies
= resolve( [ 'site' ] );
1212 if ( ex
=== undefined ) {
1213 enqueue( dependencies
, runScript
, runScript
);
1218 runScript
= undefined; // Revoke
1221 cssHandle = function () {
1222 var check
= checkCssHandles
;
1224 return function () {
1228 check
= undefined; // Revoke
1234 // Process styles (see also mw.loader.implement)
1235 // * back-compat: { <media>: css }
1236 // * back-compat: { <media>: [url, ..] }
1237 // * { "css": [css, ..] }
1238 // * { "url": { <media>: [url, ..] } }
1239 if ( registry
[ module
].style
) {
1240 for ( key
in registry
[ module
].style
) {
1241 value
= registry
[ module
].style
[ key
];
1244 if ( key
!== 'url' && key
!== 'css' ) {
1245 // Backwards compatibility, key is a media-type
1246 if ( typeof value
=== 'string' ) {
1247 // back-compat: { <media>: css }
1248 // Ignore 'media' because it isn't supported (nor was it used).
1249 // Strings are pre-wrapped in "@media". The media-type was just ""
1250 // (because it had to be set to something).
1251 // This is one of the reasons why this format is no longer used.
1252 addEmbeddedCSS( value
, cssHandle() );
1254 // back-compat: { <media>: [url, ..] }
1260 // Array of css strings in key 'css',
1261 // or back-compat array of urls from media-type
1262 if ( Array
.isArray( value
) ) {
1263 for ( i
= 0; i
< value
.length
; i
++ ) {
1264 if ( key
=== 'bc-url' ) {
1265 // back-compat: { <media>: [url, ..] }
1266 addLink( media
, value
[ i
] );
1267 } else if ( key
=== 'css' ) {
1268 // { "css": [css, ..] }
1269 addEmbeddedCSS( value
[ i
], cssHandle() );
1272 // Not an array, but a regular object
1273 // Array of urls inside media-type key
1274 } else if ( typeof value
=== 'object' ) {
1275 // { "url": { <media>: [url, ..] } }
1276 for ( media
in value
) {
1277 urls
= value
[ media
];
1278 for ( i
= 0; i
< urls
.length
; i
++ ) {
1279 addLink( media
, urls
[ i
] );
1287 cssHandlesRegistered
= true;
1291 function sortQuery( o
) {
1300 for ( key
= 0; key
< a
.length
; key
++ ) {
1301 sorted
[ a
[ key
] ] = o
[ a
[ key
] ];
1307 * Converts a module map of the form `{ foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }`
1308 * to a query string of the form `foo.bar,baz|bar.baz,quux`.
1310 * See `ResourceLoader::makePackedModulesString()` in PHP, of which this is a port.
1311 * On the server, unpacking is done by `ResourceLoaderContext::expandModuleNames()`.
1313 * Note: This is only half of the logic, the other half has to be in #batchRequest(),
1314 * because its implementation needs to keep track of potential string size in order
1315 * to decide when to split the requests due to url size.
1318 * @param {Object} moduleMap Module map
1320 * @return {string} return.str Module query string
1321 * @return {Array} return.list List of module names in matching order
1323 function buildModulesString( moduleMap
) {
1328 function restore( suffix
) {
1332 for ( prefix
in moduleMap
) {
1333 p
= prefix
=== '' ? '' : prefix
+ '.';
1334 str
.push( p
+ moduleMap
[ prefix
].join( ',' ) );
1335 list
.push
.apply( list
, moduleMap
[ prefix
].map( restore
) );
1338 str
: str
.join( '|' ),
1344 * Resolve indexed dependencies.
1346 * ResourceLoader uses an optimization to save space which replaces module names in
1347 * dependency lists with the index of that module within the array of module
1348 * registration data if it exists. The benefit is a significant reduction in the data
1349 * size of the startup module. This function changes those dependency lists back to
1350 * arrays of strings.
1353 * @param {Array} modules Modules array
1355 function resolveIndexedDependencies( modules
) {
1357 function resolveIndex( dep
) {
1358 return typeof dep
=== 'number' ? modules
[ dep
][ 0 ] : dep
;
1360 for ( i
= 0; i
< modules
.length
; i
++ ) {
1361 deps
= modules
[ i
][ 2 ];
1363 for ( j
= 0; j
< deps
.length
; j
++ ) {
1364 deps
[ j
] = resolveIndex( deps
[ j
] );
1372 * @param {Object} params Map of parameter names to values
1375 function makeQueryString( params
) {
1376 return Object
.keys( params
).map( function ( key
) {
1377 return encodeURIComponent( key
) + '=' + encodeURIComponent( params
[ key
] );
1382 * Create network requests for a batch of modules.
1384 * This is an internal method for #work(). This must not be called directly
1385 * unless the modules are already registered, and no request is in progress,
1386 * and the module state has already been set to `loading`.
1389 * @param {string[]} batch
1391 function batchRequest( batch
) {
1392 var reqBase
, splits
, maxQueryLength
, b
, bSource
, bGroup
, bSourceGroup
,
1393 source
, group
, i
, modules
, sourceLoadScript
,
1394 currReqBase
, currReqBaseLength
, moduleMap
, currReqModules
, l
,
1395 lastDotIndex
, prefix
, suffix
, bytesAdded
;
1398 * Start the currently drafted request to the server.
1402 function doRequest() {
1403 // Optimisation: Inherit (Object.create), not copy ($.extend)
1404 var query
= Object
.create( currReqBase
),
1405 packed
= buildModulesString( moduleMap
);
1406 query
.modules
= packed
.str
;
1407 // The packing logic can change the effective order, even if the input was
1408 // sorted. As such, the call to getCombinedVersion() must use this
1409 // effective order, instead of currReqModules, as otherwise the combined
1410 // version will not match the hash expected by the server based on
1411 // combining versions from the module query string in-order. (T188076)
1412 query
.version
= getCombinedVersion( packed
.list
);
1413 query
= sortQuery( query
);
1414 addScript( sourceLoadScript
+ '?' + makeQueryString( query
) );
1417 if ( !batch
.length
) {
1421 // Always order modules alphabetically to help reduce cache
1422 // misses for otherwise identical content.
1425 // Query parameters common to all requests
1427 skin
: mw
.config
.get( 'skin' ),
1428 lang
: mw
.config
.get( 'wgUserLanguage' ),
1429 debug
: mw
.config
.get( 'debug' )
1431 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', 2000 );
1433 // Split module list by source and by group.
1435 for ( b
= 0; b
< batch
.length
; b
++ ) {
1436 bSource
= registry
[ batch
[ b
] ].source
;
1437 bGroup
= registry
[ batch
[ b
] ].group
;
1438 if ( !hasOwn
.call( splits
, bSource
) ) {
1439 splits
[ bSource
] = {};
1441 if ( !hasOwn
.call( splits
[ bSource
], bGroup
) ) {
1442 splits
[ bSource
][ bGroup
] = [];
1444 bSourceGroup
= splits
[ bSource
][ bGroup
];
1445 bSourceGroup
.push( batch
[ b
] );
1448 for ( source
in splits
) {
1450 sourceLoadScript
= sources
[ source
];
1452 for ( group
in splits
[ source
] ) {
1454 // Cache access to currently selected list of
1455 // modules for this group from this source.
1456 modules
= splits
[ source
][ group
];
1458 // Query parameters common to requests for this module group
1459 // Optimisation: Inherit (Object.create), not copy ($.extend)
1460 currReqBase
= Object
.create( reqBase
);
1461 // User modules require a user name in the query string.
1462 if ( group
=== 'user' && mw
.config
.get( 'wgUserName' ) !== null ) {
1463 currReqBase
.user
= mw
.config
.get( 'wgUserName' );
1466 // In addition to currReqBase, doRequest() will also add 'modules' and 'version'.
1467 // > '&modules='.length === 9
1468 // > '&version=1234567'.length === 16
1470 currReqBaseLength
= makeQueryString( currReqBase
).length
+ 25;
1472 // We may need to split up the request to honor the query string length limit,
1473 // so build it piece by piece.
1474 l
= currReqBaseLength
;
1475 moduleMap
= {}; // { prefix: [ suffixes ] }
1476 currReqModules
= [];
1478 for ( i
= 0; i
< modules
.length
; i
++ ) {
1479 // Determine how many bytes this module would add to the query string
1480 lastDotIndex
= modules
[ i
].lastIndexOf( '.' );
1481 // If lastDotIndex is -1, substr() returns an empty string
1482 prefix
= modules
[ i
].substr( 0, lastDotIndex
);
1483 suffix
= modules
[ i
].slice( lastDotIndex
+ 1 );
1484 bytesAdded
= hasOwn
.call( moduleMap
, prefix
) ?
1485 suffix
.length
+ 3 : // '%2C'.length == 3
1486 modules
[ i
].length
+ 3; // '%7C'.length == 3
1488 // If the url would become too long, create a new one, but don't create empty requests
1489 if ( maxQueryLength
> 0 && currReqModules
.length
&& l
+ bytesAdded
> maxQueryLength
) {
1490 // Dispatch what we've got...
1492 // .. and start again.
1493 l
= currReqBaseLength
;
1495 currReqModules
= [];
1497 mw
.track( 'resourceloader.splitRequest', { maxQueryLength
: maxQueryLength
} );
1499 if ( !hasOwn
.call( moduleMap
, prefix
) ) {
1500 moduleMap
[ prefix
] = [];
1503 moduleMap
[ prefix
].push( suffix
);
1504 currReqModules
.push( modules
[ i
] );
1506 // If there's anything left in moduleMap, request that too
1507 if ( currReqModules
.length
) {
1516 * @param {string[]} implementations Array containing pieces of JavaScript code in the
1517 * form of calls to mw.loader#implement().
1518 * @param {Function} cb Callback in case of failure
1519 * @param {Error} cb.err
1521 function asyncEval( implementations
, cb
) {
1522 if ( !implementations
.length
) {
1525 mw
.requestIdleCallback( function () {
1527 domEval( implementations
.join( ';' ) );
1535 * Make a versioned key for a specific module.
1538 * @param {string} module Module name
1539 * @return {string|null} Module key in format '`[name]@[version]`',
1540 * or null if the module does not exist
1542 function getModuleKey( module
) {
1543 return hasOwn
.call( registry
, module
) ?
1544 ( module
+ '@' + registry
[ module
].version
) : null;
1549 * @param {string} key Module name or '`[name]@[version]`'
1552 function splitModuleKey( key
) {
1553 var index
= key
.indexOf( '@' );
1554 if ( index
=== -1 ) {
1561 name
: key
.slice( 0, index
),
1562 version
: key
.slice( index
+ 1 )
1566 /* Public Members */
1569 * The module registry is exposed as an aid for debugging and inspecting page
1570 * state; it is not a public interface for modifying the registry.
1576 moduleRegistry
: registry
,
1579 * @inheritdoc #newStyleTag
1582 addStyleTag
: newStyleTag
,
1589 * Start loading of all queued module dependencies.
1594 var q
, batch
, implementations
, sourceModules
;
1598 // Appends a list of modules from the queue to the batch
1599 for ( q
= 0; q
< queue
.length
; q
++ ) {
1600 // Only load modules which are registered
1601 if ( hasOwn
.call( registry
, queue
[ q
] ) && registry
[ queue
[ q
] ].state
=== 'registered' ) {
1602 // Prevent duplicate entries
1603 if ( batch
.indexOf( queue
[ q
] ) === -1 ) {
1604 batch
.push( queue
[ q
] );
1605 // Mark registered modules as loading
1606 registry
[ queue
[ q
] ].state
= 'loading';
1611 // Now that the queue has been processed into a batch, clear the queue.
1612 // This MUST happen before we initiate any eval or network request. Otherwise,
1613 // it is possible for a cached script to instantly trigger the same work queue
1614 // again; all before we've cleared it causing each request to include modules
1615 // which are already loaded.
1618 if ( !batch
.length
) {
1622 mw
.loader
.store
.init();
1623 if ( mw
.loader
.store
.enabled
) {
1624 implementations
= [];
1626 batch
= batch
.filter( function ( module
) {
1627 var implementation
= mw
.loader
.store
.get( module
);
1628 if ( implementation
) {
1629 implementations
.push( implementation
);
1630 sourceModules
.push( module
);
1635 asyncEval( implementations
, function ( err
) {
1637 // Not good, the cached mw.loader.implement calls failed! This should
1638 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1639 // Depending on how corrupt the string is, it is likely that some
1640 // modules' implement() succeeded while the ones after the error will
1641 // never run and leave their modules in the 'loading' state forever.
1642 mw
.loader
.store
.stats
.failed
++;
1644 // Since this is an error not caused by an individual module but by
1645 // something that infected the implement call itself, don't take any
1646 // risks and clear everything in this cache.
1647 mw
.loader
.store
.clear();
1649 mw
.trackError( 'resourceloader.exception', {
1651 source
: 'store-eval'
1653 // Re-add the failed ones that are still pending back to the batch
1654 failed
= sourceModules
.filter( function ( module
) {
1655 return registry
[ module
].state
=== 'loading';
1657 batchRequest( failed
);
1661 batchRequest( batch
);
1665 * Register a source.
1667 * The #work() method will use this information to split up requests by source.
1669 * mw.loader.addSource( 'mediawikiwiki', '//www.mediawiki.org/w/load.php' );
1671 * @param {string|Object} id Source ID, or object mapping ids to load urls
1672 * @param {string} loadUrl Url to a load.php end point
1673 * @throws {Error} If source id is already registered
1675 addSource: function ( id
, loadUrl
) {
1677 // Allow multiple additions
1678 if ( typeof id
=== 'object' ) {
1679 for ( source
in id
) {
1680 mw
.loader
.addSource( source
, id
[ source
] );
1685 if ( hasOwn
.call( sources
, id
) ) {
1686 throw new Error( 'source already registered: ' + id
);
1689 sources
[ id
] = loadUrl
;
1693 * Register a module, letting the system know about it and its properties.
1695 * The startup modules contain calls to this method.
1697 * When using multiple module registration by passing an array, dependencies that
1698 * are specified as references to modules within the array will be resolved before
1699 * the modules are registered.
1701 * @param {string|Array} module Module name or array of arrays, each containing
1702 * a list of arguments compatible with this method
1703 * @param {string|number} version Module version hash (falls backs to empty string)
1704 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1705 * @param {string|Array} dependencies One string or array of strings of module
1706 * names on which this module depends.
1707 * @param {string} [group=null] Group which the module is in
1708 * @param {string} [source='local'] Name of the source
1709 * @param {string} [skip=null] Script body of the skip function
1711 register: function ( module
, version
, dependencies
, group
, source
, skip
) {
1713 // Allow multiple registration
1714 if ( typeof module
=== 'object' ) {
1715 resolveIndexedDependencies( module
);
1716 for ( i
= 0; i
< module
.length
; i
++ ) {
1717 // module is an array of module names
1718 if ( typeof module
[ i
] === 'string' ) {
1719 mw
.loader
.register( module
[ i
] );
1720 // module is an array of arrays
1721 } else if ( typeof module
[ i
] === 'object' ) {
1722 mw
.loader
.register
.apply( mw
.loader
, module
[ i
] );
1727 if ( hasOwn
.call( registry
, module
) ) {
1728 throw new Error( 'module already registered: ' + module
);
1730 if ( typeof dependencies
=== 'string' ) {
1731 // A single module name
1732 deps
= [ dependencies
];
1733 } else if ( typeof dependencies
=== 'object' ) {
1734 // Array of module names
1735 deps
= dependencies
;
1737 // List the module as registered
1738 registry
[ module
] = {
1739 // Exposed to execute() for mw.loader.implement() closures.
1740 // Import happens via require().
1744 version
: version
!== undefined ? String( version
) : '',
1745 dependencies
: deps
|| [],
1746 group
: typeof group
=== 'string' ? group
: null,
1747 source
: typeof source
=== 'string' ? source
: 'local',
1748 state
: 'registered',
1749 skip
: typeof skip
=== 'string' ? skip
: null
1754 * Implement a module given the components that make up the module.
1756 * When #load() or #using() requests one or more modules, the server
1757 * response contain calls to this function.
1759 * @param {string} module Name of module and current module version. Formatted
1760 * as '`[name]@[version]`". This version should match the requested version
1761 * (from #batchRequest and #registry). This avoids race conditions (T117587).
1762 * For back-compat with MediaWiki 1.27 and earlier, the version may be omitted.
1763 * @param {Function|Array|string} [script] Function with module code, list of URLs
1764 * to load via `<script src>`, or string of module code for `$.globalEval()`.
1765 * @param {Object} [style] Should follow one of the following patterns:
1767 * { "css": [css, ..] }
1768 * { "url": { <media>: [url, ..] } }
1770 * And for backwards compatibility (needs to be supported forever due to caching):
1773 * { <media>: [url, ..] }
1775 * The reason css strings are not concatenated anymore is T33676. We now check
1776 * whether it's safe to extend the stylesheet.
1779 * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1780 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1782 implement: function ( module
, script
, style
, messages
, templates
) {
1783 var split
= splitModuleKey( module
),
1785 version
= split
.version
;
1786 // Automatically register module
1787 if ( !hasOwn
.call( registry
, name
) ) {
1788 mw
.loader
.register( name
);
1790 // Check for duplicate implementation
1791 if ( hasOwn
.call( registry
, name
) && registry
[ name
].script
!== undefined ) {
1792 throw new Error( 'module already implemented: ' + name
);
1795 // Without this reset, if there is a version mismatch between the
1796 // requested and received module version, then mw.loader.store would
1797 // cache the response under the requested key. Thus poisoning the cache
1798 // indefinitely with a stale value. (T117587)
1799 registry
[ name
].version
= version
;
1801 // Attach components
1802 registry
[ name
].script
= script
|| null;
1803 registry
[ name
].style
= style
|| null;
1804 registry
[ name
].messages
= messages
|| null;
1805 registry
[ name
].templates
= templates
|| null;
1806 // The module may already have been marked as erroneous
1807 if ( registry
[ name
].state
!== 'error' && registry
[ name
].state
!== 'missing' ) {
1808 registry
[ name
].state
= 'loaded';
1809 if ( allReady( registry
[ name
].dependencies
) ) {
1816 * Load an external script or one or more modules.
1818 * This method takes a list of unrelated modules. Use cases:
1820 * - A web page will be composed of many different widgets. These widgets independently
1821 * queue their ResourceLoader modules (`OutputPage::addModules()`). If any of them
1822 * have problems, or are no longer known (e.g. cached HTML), the other modules
1823 * should still be loaded.
1824 * - This method is used for preloading, which must not throw. Later code that
1825 * calls #using() will handle the error.
1827 * @param {string|Array} modules Either the name of a module, array of modules,
1828 * or a URL of an external script or style
1829 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
1830 * external script or style; acceptable values are "text/css" and
1831 * "text/javascript"; if no type is provided, text/javascript is assumed.
1833 load: function ( modules
, type
) {
1836 // Allow calling with a url or single dependency as a string
1837 if ( typeof modules
=== 'string' ) {
1838 // "https://example.org/x.js", "http://example.org/x.js", "//example.org/x.js", "/x.js"
1839 if ( /^(https?:)?\/?\//.test( modules
) ) {
1840 if ( type
=== 'text/css' ) {
1841 l
= document
.createElement( 'link' );
1842 l
.rel
= 'stylesheet';
1844 document
.head
.appendChild( l
);
1847 if ( type
=== 'text/javascript' || type
=== undefined ) {
1848 addScript( modules
);
1852 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type
);
1854 // Called with single module
1855 modules
= [ modules
];
1858 // Filter out top-level modules that are unknown or failed to load before.
1859 filtered
= modules
.filter( function ( module
) {
1860 var state
= mw
.loader
.getState( module
);
1861 return state
!== 'error' && state
!== 'missing';
1863 // Resolve remaining list using the known dependency tree.
1864 // This also filters out modules with unknown dependencies. (T36853)
1865 filtered
= resolveStubbornly( filtered
);
1866 // Some modules are not yet ready, add to module load queue.
1867 enqueue( filtered
, undefined, undefined );
1871 * Change the state of one or more modules.
1873 * @param {string|Object} module Module name or object of module name/state pairs
1874 * @param {string} state State name
1876 state: function ( module
, state
) {
1879 if ( typeof module
=== 'object' ) {
1880 for ( m
in module
) {
1881 mw
.loader
.state( m
, module
[ m
] );
1885 if ( !hasOwn
.call( registry
, module
) ) {
1886 mw
.loader
.register( module
);
1888 registry
[ module
].state
= state
;
1889 if ( state
=== 'ready' || state
=== 'error' || state
=== 'missing' ) {
1890 // Make sure pending modules depending on this one get executed if their
1891 // dependencies are now fulfilled!
1892 handlePending( module
);
1897 * Get the version of a module.
1899 * @param {string} module Name of module
1900 * @return {string|null} The version, or null if the module (or its version) is not
1903 getVersion: function ( module
) {
1904 return hasOwn
.call( registry
, module
) ? registry
[ module
].version
: null;
1908 * Get the state of a module.
1910 * @param {string} module Name of module
1911 * @return {string|null} The state, or null if the module (or its state) is not
1914 getState: function ( module
) {
1915 return hasOwn
.call( registry
, module
) ? registry
[ module
].state
: null;
1919 * Get the names of all registered modules.
1923 getModuleNames: function () {
1924 return Object
.keys( registry
);
1928 * Get the exported value of a module.
1930 * This static method is publicly exposed for debugging purposes
1931 * only and must not be used in production code. In production code,
1932 * please use the dynamically provided `require()` function instead.
1934 * In case of lazy-loaded modules via mw.loader#using(), the returned
1935 * Promise provides the function, see #using() for examples.
1939 * @param {string} moduleName Module name
1940 * @return {Mixed} Exported value
1942 require: function ( moduleName
) {
1943 var state
= mw
.loader
.getState( moduleName
);
1945 // Only ready modules can be required
1946 if ( state
!== 'ready' ) {
1947 // Module may've forgotten to declare a dependency
1948 throw new Error( 'Module "' + moduleName
+ '" is not loaded.' );
1951 return registry
[ moduleName
].module
.exports
;
1955 * On browsers that implement the localStorage API, the module store serves as a
1956 * smart complement to the browser cache. Unlike the browser cache, the module store
1957 * can slice a concatenated response from ResourceLoader into its constituent
1958 * modules and cache each of them separately, using each module's versioning scheme
1959 * to determine when the cache should be invalidated.
1962 * @class mw.loader.store
1965 // Whether the store is in use on this page.
1968 // Modules whose string representation exceeds 100 kB are
1969 // ineligible for storage. See bug T66721.
1970 MODULE_SIZE_MAX
: 100 * 1000,
1972 // The contents of the store, mapping '[name]@[version]' keys
1973 // to module implementations.
1977 stats
: { hits
: 0, misses
: 0, expired
: 0, failed
: 0 },
1980 * Construct a JSON-serializable object representing the content of the store.
1982 * @return {Object} Module store contents.
1984 toJSON: function () {
1985 return { items
: mw
.loader
.store
.items
, vary
: mw
.loader
.store
.getVary() };
1989 * Get the localStorage key for the entire module store. The key references
1990 * $wgDBname to prevent clashes between wikis which share a common host.
1992 * @return {string} localStorage item key
1994 getStoreKey: function () {
1995 return 'MediaWikiModuleStore:' + mw
.config
.get( 'wgDBname' );
1999 * Get a key on which to vary the module cache.
2001 * @return {string} String of concatenated vary conditions.
2003 getVary: function () {
2005 mw
.config
.get( 'skin' ),
2006 mw
.config
.get( 'wgResourceLoaderStorageVersion' ),
2007 mw
.config
.get( 'wgUserLanguage' )
2012 * Initialize the store.
2014 * Retrieves store from localStorage and (if successfully retrieved) decoding
2015 * the stored JSON value to a plain object.
2017 * The try / catch block is used for JSON & localStorage feature detection.
2018 * See the in-line documentation for Modernizr's localStorage feature detection
2019 * code for a full account of why we need a try / catch:
2020 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2025 if ( mw
.loader
.store
.enabled
!== null ) {
2031 // Disabled because localStorage quotas are tight and (in Firefox's case)
2032 // shared by multiple origins.
2033 // See T66721, and <https://bugzilla.mozilla.org/show_bug.cgi?id=1064466>.
2034 /Firefox|Opera/.test( navigator
.userAgent
) ||
2036 // Disabled by configuration.
2037 !mw
.config
.get( 'wgResourceLoaderStorageEnabled' )
2039 // Clear any previous store to free up space. (T66721)
2040 mw
.loader
.store
.clear();
2041 mw
.loader
.store
.enabled
= false;
2044 if ( mw
.config
.get( 'debug' ) ) {
2045 // Disable module store in debug mode
2046 mw
.loader
.store
.enabled
= false;
2051 raw
= localStorage
.getItem( mw
.loader
.store
.getStoreKey() );
2052 // If we get here, localStorage is available; mark enabled
2053 mw
.loader
.store
.enabled
= true;
2054 data
= JSON
.parse( raw
);
2055 if ( data
&& typeof data
.items
=== 'object' && data
.vary
=== mw
.loader
.store
.getVary() ) {
2056 mw
.loader
.store
.items
= data
.items
;
2060 mw
.trackError( 'resourceloader.exception', {
2062 source
: 'store-localstorage-init'
2066 if ( raw
=== undefined ) {
2067 // localStorage failed; disable store
2068 mw
.loader
.store
.enabled
= false;
2070 mw
.loader
.store
.update();
2075 * Retrieve a module from the store and update cache hit stats.
2077 * @param {string} module Module name
2078 * @return {string|boolean} Module implementation or false if unavailable
2080 get: function ( module
) {
2083 if ( !mw
.loader
.store
.enabled
) {
2087 key
= getModuleKey( module
);
2088 if ( key
in mw
.loader
.store
.items
) {
2089 mw
.loader
.store
.stats
.hits
++;
2090 return mw
.loader
.store
.items
[ key
];
2092 mw
.loader
.store
.stats
.misses
++;
2097 * Stringify a module and queue it for storage.
2099 * @param {string} module Module name
2100 * @param {Object} descriptor The module's descriptor as set in the registry
2101 * @return {boolean} Module was set
2103 set: function ( module
, descriptor
) {
2106 if ( !mw
.loader
.store
.enabled
) {
2110 key
= getModuleKey( module
);
2113 // Already stored a copy of this exact version
2114 key
in mw
.loader
.store
.items
||
2115 // Module failed to load
2116 descriptor
.state
!== 'ready' ||
2117 // Unversioned, private, or site-/user-specific
2118 !descriptor
.version
||
2119 descriptor
.group
=== 'private' ||
2120 descriptor
.group
=== 'user' ||
2121 // Partial descriptor
2122 // (e.g. skipped module, or style module with state=ready)
2123 [ descriptor
.script
, descriptor
.style
, descriptor
.messages
,
2124 descriptor
.templates
].indexOf( undefined ) !== -1
2132 JSON
.stringify( key
),
2133 typeof descriptor
.script
=== 'function' ?
2134 String( descriptor
.script
) :
2135 JSON
.stringify( descriptor
.script
),
2136 JSON
.stringify( descriptor
.style
),
2137 JSON
.stringify( descriptor
.messages
),
2138 JSON
.stringify( descriptor
.templates
)
2140 // Attempted workaround for a possible Opera bug (bug T59567).
2141 // This regex should never match under sane conditions.
2142 if ( /^\s*\(/.test( args
[ 1 ] ) ) {
2143 args
[ 1 ] = 'function' + args
[ 1 ];
2144 mw
.trackError( 'resourceloader.assert', { source
: 'bug-T59567' } );
2147 mw
.trackError( 'resourceloader.exception', {
2149 source
: 'store-localstorage-json'
2154 src
= 'mw.loader.implement(' + args
.join( ',' ) + ');';
2155 if ( src
.length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2158 mw
.loader
.store
.items
[ key
] = src
;
2159 mw
.loader
.store
.update();
2164 * Iterate through the module store, removing any item that does not correspond
2165 * (in name and version) to an item in the module registry.
2167 * @return {boolean} Store was pruned
2169 prune: function () {
2172 if ( !mw
.loader
.store
.enabled
) {
2176 for ( key
in mw
.loader
.store
.items
) {
2177 module
= key
.slice( 0, key
.indexOf( '@' ) );
2178 if ( getModuleKey( module
) !== key
) {
2179 mw
.loader
.store
.stats
.expired
++;
2180 delete mw
.loader
.store
.items
[ key
];
2181 } else if ( mw
.loader
.store
.items
[ key
].length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2182 // This value predates the enforcement of a size limit on cached modules.
2183 delete mw
.loader
.store
.items
[ key
];
2190 * Clear the entire module store right now.
2192 clear: function () {
2193 mw
.loader
.store
.items
= {};
2195 localStorage
.removeItem( mw
.loader
.store
.getStoreKey() );
2196 } catch ( ignored
) {}
2200 * Sync in-memory store back to localStorage.
2202 * This function debounces updates. When called with a flush already pending,
2203 * the call is coalesced into the pending update. The call to
2204 * localStorage.setItem will be naturally deferred until the page is quiescent.
2206 * Because localStorage is shared by all pages from the same origin, if multiple
2207 * pages are loaded with different module sets, the possibility exists that
2208 * modules saved by one page will be clobbered by another. But the impact would
2209 * be minor and the problem would be corrected by subsequent page views.
2213 update
: ( function () {
2214 var hasPendingWrite
= false;
2216 function flushWrites() {
2218 if ( !hasPendingWrite
|| !mw
.loader
.store
.enabled
) {
2222 mw
.loader
.store
.prune();
2223 key
= mw
.loader
.store
.getStoreKey();
2225 // Replacing the content of the module store might fail if the new
2226 // contents would exceed the browser's localStorage size limit. To
2227 // avoid clogging the browser with stale data, always remove the old
2228 // value before attempting to set the new one.
2229 localStorage
.removeItem( key
);
2230 data
= JSON
.stringify( mw
.loader
.store
);
2231 localStorage
.setItem( key
, data
);
2233 mw
.trackError( 'resourceloader.exception', {
2235 source
: 'store-localstorage-update'
2239 hasPendingWrite
= false;
2242 return function () {
2243 if ( !hasPendingWrite
) {
2244 hasPendingWrite
= true;
2245 mw
.requestIdleCallback( flushWrites
);
2253 // Skeleton user object, extended by the 'mediawiki.user' module.
2260 * @property {mw.Map}
2264 * @property {mw.Map}
2269 // OOUI widgets specific to MediaWiki
2274 // Attach to window and globally alias
2275 window
.mw
= window
.mediaWiki
= mw
;