2 * Base library for MediaWiki.
4 * Exposed globally as `mw`, with `mediaWiki` as alias.
7 * @alternateClassName mediaWiki
10 /* global $VARS, $CODE */
15 var mw
, StringSet
, log
,
16 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 var hash
= 0x811C9DC5,
34 /* eslint-disable no-bitwise */
35 for ( ; 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 ) {
44 /* eslint-enable no-bitwise */
49 function defineFallbacks() {
50 // <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set>
55 StringSet
= window
.Set
|| function () {
56 var set = Object
.create( null );
58 add: function ( value
) {
61 has: function ( value
) {
69 * Alias property to the global object.
76 * @param {Mixed} value
78 function setGlobalMapValue( map
, key
, value
) {
79 map
.values
[ key
] = value
;
84 // Deprecation notice for mw.config globals (T58550, T72470)
85 map
=== mw
.config
&& 'Use mw.config instead.'
90 * Log a message to window.console, if possible.
92 * Useful to force logging of some errors that are otherwise hard to detect (i.e., this logs
93 * also in production mode). Gets console references in each invocation instead of caching the
94 * reference, so that debugging tools loaded later are supported (e.g. Firebug Lite in IE).
97 * @param {string} topic Stream name passed by mw.track
98 * @param {Object} data Data passed by mw.track
99 * @param {Error} [data.exception]
100 * @param {string} data.source Error source
101 * @param {string} [data.module] Name of module which caused the error
103 function logError( topic
, data
) {
106 console
= window
.console
;
108 if ( console
&& console
.log
) {
109 msg
= ( e
? 'Exception' : 'Error' ) +
110 ' in ' + data
.source
+
111 ( data
.module
? ' in module ' + data
.module
: '' ) +
116 // If we have an exception object, log it to the warning channel to trigger
117 // proper stacktraces in browsers that support it.
118 if ( e
&& console
.warn
) {
125 * Create an object that can be read from or written to via methods that allow
126 * interaction both with single and multiple properties at once.
132 * @param {boolean} [global=false] Whether to synchronise =values to the global
133 * window object (for backwards-compatibility with mw.config; T72470). Values are
134 * copied in one direction only. Changes to globals do not reflect in the map.
136 function Map( global
) {
137 this.values
= Object
.create( null );
138 if ( global
=== true ) {
139 // Override #set to also set the global variable
140 this.set = function ( selection
, value
) {
142 if ( arguments
.length
> 1 ) {
143 if ( typeof selection
=== 'string' ) {
144 setGlobalMapValue( this, selection
, value
);
147 } else if ( typeof selection
=== 'object' ) {
148 for ( s
in selection
) {
149 setGlobalMapValue( this, s
, selection
[ s
] );
162 * Get the value of one or more keys.
164 * If called with no arguments, all values are returned.
166 * @param {string|Array} [selection] Key or array of keys to retrieve values for.
167 * @param {Mixed} [fallback=null] Value for keys that don't exist.
168 * @return {Mixed|Object|null} If selection was a string, returns the value,
169 * If selection was an array, returns an object of key/values.
170 * If no selection is passed, a new object with all key/values is returned.
172 get: function ( selection
, fallback
) {
174 fallback
= arguments
.length
> 1 ? fallback
: null;
176 if ( Array
.isArray( selection
) ) {
178 for ( i
= 0; i
< selection
.length
; i
++ ) {
179 if ( typeof selection
[ i
] === 'string' ) {
180 results
[ selection
[ i
] ] = selection
[ i
] in this.values
?
181 this.values
[ selection
[ i
] ] :
188 if ( typeof selection
=== 'string' ) {
189 return selection
in this.values
?
190 this.values
[ selection
] :
194 if ( selection
=== undefined ) {
196 for ( i
in this.values
) {
197 results
[ i
] = this.values
[ i
];
202 // Invalid selection key
207 * Set one or more key/value pairs.
209 * @param {string|Object} selection Key to set value for, or object mapping keys to values
210 * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
211 * @return {boolean} True on success, false on failure
213 set: function ( selection
, value
) {
215 // Use `arguments.length` because `undefined` is also a valid value.
216 if ( arguments
.length
> 1 ) {
218 if ( typeof selection
=== 'string' ) {
219 this.values
[ selection
] = value
;
222 } else if ( typeof selection
=== 'object' ) {
224 for ( s
in selection
) {
225 this.values
[ s
] = selection
[ s
];
233 * Check if one or more keys exist.
235 * @param {Mixed} selection Key or array of keys to check
236 * @return {boolean} True if the key(s) exist
238 exists: function ( selection
) {
240 if ( Array
.isArray( selection
) ) {
241 for ( i
= 0; i
< selection
.length
; i
++ ) {
242 if ( typeof selection
[ i
] !== 'string' || !( selection
[ i
] in this.values
) ) {
248 return typeof selection
=== 'string' && selection
in this.values
;
254 log
= ( function () {
256 * Write a verbose message to the browser's console in debug mode.
258 * This method is mainly intended for verbose logging. It is a no-op in production mode.
259 * In ResourceLoader debug mode, it will use the browser's console if available, with
260 * fallback to creating a console interface in the DOM and logging messages there.
262 * See {@link mw.log} for other logging methods.
265 * @param {...string} msg Messages to output to console.
267 var log = function () {},
268 console
= window
.console
;
270 // Note: Keep list of methods in sync with restoration in mediawiki.log.js
271 // when adding or removing mw.log methods below!
274 * Collection of methods to help log messages to the console.
281 * Write a message to the browser console's warning channel.
283 * This method is a no-op in browsers that don't implement the Console API.
285 * @param {...string} msg Messages to output to console
287 log
.warn
= console
&& console
.warn
?
288 Function
.prototype.bind
.call( console
.warn
, console
) :
292 * Write a message to the browser console's error channel.
294 * Most browsers also print a stacktrace when calling this method if the
295 * argument is an Error object.
297 * This method is a no-op in browsers that don't implement the Console API.
300 * @param {...Mixed} msg Messages to output to console
302 log
.error
= console
&& console
.error
?
303 Function
.prototype.bind
.call( console
.error
, console
) :
307 * Create a property on a host object that, when accessed, will produce
308 * a deprecation warning in the console.
310 * @param {Object} obj Host object of deprecated property
311 * @param {string} key Name of property to create in `obj`
312 * @param {Mixed} val The value this property should return when accessed
313 * @param {string} [msg] Optional text to include in the deprecation message
314 * @param {string} [logName] Name for the feature for logging and tracking
315 * purposes. Except for properties of the window object, tracking is only
316 * enabled if logName is set.
318 log
.deprecate = function ( obj
, key
, val
, msg
, logName
) {
320 function maybeLog() {
321 var name
= logName
|| key
,
322 trace
= new Error().stack
;
324 stacks
= new StringSet();
326 if ( !stacks
.has( trace
) ) {
328 if ( logName
|| obj
=== window
) {
329 mw
.track( 'mw.deprecate', name
);
332 'Use of "' + name
+ '" is deprecated.' + ( msg
? ' ' + msg
: '' )
336 // Support: Safari 5.0
337 // Throws "not supported on DOM Objects" for Node or Element objects (incl. document)
338 // Safari 4.0 doesn't have this method, and it was fixed in Safari 5.1.
340 Object
.defineProperty( obj
, key
, {
347 set: function ( newVal
) {
364 redefineFallbacksForTest: function () {
365 if ( !window
.QUnit
) {
366 throw new Error( 'Not allowed' );
372 * Get the current time, measured in milliseconds since January 1, 1970 (UTC).
374 * On browsers that implement the Navigation Timing API, this function will produce
375 * floating-point values with microsecond precision that are guaranteed to be monotonic.
376 * On all other browsers, it will fall back to using `Date`.
378 * @return {number} Current time
381 // Optimisation: Make startup initialisation faster by defining the
382 // shortcut on first call, not at module definition.
383 var perf
= window
.performance
,
384 navStart
= perf
&& perf
.timing
&& perf
.timing
.navigationStart
;
386 // Define the relevant shortcut
387 mw
.now
= navStart
&& perf
.now
?
388 function () { return navStart
+ perf
.now(); } :
395 * List of all analytic events emitted so far.
397 * Exposed only for use by mediawiki.base.
404 track: function ( topic
, data
) {
405 mw
.trackQueue
.push( { topic
: topic
, timeStamp
: mw
.now(), data
: data
} );
406 // This method is extended by mediawiki.base to also fire events.
410 * Track an early error event via mw.track and send it to the window console.
413 * @param {string} topic Topic name
414 * @param {Object} data Data describing the event, encoded as an object; see mw#logError
416 trackError: function ( topic
, data
) {
417 mw
.track( topic
, data
);
418 logError( topic
, data
);
421 // Expose Map constructor
425 * Map of configuration values.
427 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
430 * If `$wgLegacyJavaScriptGlobals` is true, this Map will add its values to the
431 * global `window` object.
433 * @property {mw.Map} config
435 // Dummy placeholder later assigned in ResourceLoaderStartUpModule
439 * Empty object for third-party libraries, for cases where you don't
440 * want to add a new global, or the global is bad and needs containment
448 * Access container for deprecated functionality that can be moved from
449 * from their legacy location and attached to this object (e.g. a global
450 * function that is deprecated and as stop-gap can be exposed through here).
452 * This was reserved for future use but never ended up being used.
454 * @deprecated since 1.22 Let deprecated identifiers keep their original name
455 * and use mw.log#deprecate to create an access container for tracking.
461 * Store for messages.
468 * Store for templates associated with a module.
472 templates
: new Map(),
478 * Client for ResourceLoader server end point.
480 * This client is in charge of maintaining the module registry and state
481 * machine, initiating network (batch) requests for loading modules, as
482 * well as dependency resolution and execution of source code.
484 * For more information, refer to
485 * <https://www.mediawiki.org/wiki/ResourceLoader/Features>
490 loader
: ( function () {
493 * Fired via mw.track on various resource loading errors.
495 * @event resourceloader_exception
496 * @param {Error|Mixed} e The error that was thrown. Almost always an Error
497 * object, but in theory module code could manually throw something else, and that
498 * might also end up here.
499 * @param {string} [module] Name of the module which caused the error. Omitted if the
500 * error is not module-related or the module cannot be easily identified due to
502 * @param {string} source Source of the error. Possible values:
504 * - style: stylesheet error (only affects old IE where a special style loading method
506 * - load-callback: exception thrown by user callback
507 * - module-execute: exception thrown by module code
508 * - resolve: failed to sort dependencies for a module in mw.loader.load
509 * - store-eval: could not evaluate module code cached in localStorage
510 * - store-localstorage-init: localStorage or JSON parse error in mw.loader.store.init
511 * - store-localstorage-json: JSON conversion error in mw.loader.store
512 * - store-localstorage-update: localStorage conversion error in mw.loader.store.
516 * Fired via mw.track on resource loading error conditions.
518 * @event resourceloader_assert
519 * @param {string} source Source of the error. Possible values:
521 * - bug-T59567: failed to cache script due to an Opera function -> string conversion
522 * bug; see <https://phabricator.wikimedia.org/T59567> for details
526 * Mapping of registered modules.
528 * See #implement and #execute for exact details on support for script, style and messages.
534 * // From mw.loader.register()
535 * 'version': '########' (hash)
536 * 'dependencies': ['required.foo', 'bar.also', ...]
537 * 'group': 'somegroup', (or) null
538 * 'source': 'local', (or) 'anotherwiki'
539 * 'skip': 'return !!window.Example', (or) null
540 * 'module': export Object
542 * // Set from execute() or mw.loader.state()
543 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error', or 'missing'
545 * // Optionally added at run-time by mw.loader.implement()
547 * 'script': closure, array of urls, or string
548 * 'style': { ... } (see #execute)
549 * 'messages': { 'key': 'value', ... }
556 * The module is known to the system but not yet required.
557 * Meta data is registered via mw.loader#register. Calls to that method are
558 * generated server-side by the startup module.
560 * The module was required through mw.loader (either directly or as dependency of
561 * another module). The client will fetch module contents from the server.
562 * The contents are then stashed in the registry via mw.loader#implement.
564 * The module has been loaded from the server and stashed via mw.loader#implement.
565 * Once the module has no more dependencies in-flight, the module will be executed,
566 * controlled via #requestPropagation and #doPropagation.
568 * The module is being executed.
570 * The module has been successfully executed.
572 * The module (or one of its dependencies) produced an error during execution.
574 * The module was registered client-side and requested, but the server denied knowledge
575 * of the module's existence.
580 var registry
= Object
.create( null ),
581 // Mapping of sources, keyed by source-id, values are strings.
586 // 'sourceId': 'http://example.org/w/load.php'
589 sources
= Object
.create( null ),
591 // For queueModuleScript()
592 handlingPendingRequests
= false,
593 pendingRequests
= [],
595 // List of modules to be loaded
599 * List of callback jobs waiting for modules to be ready.
601 * Jobs are created by #enqueue() and run by #doPropagation().
602 * Typically when a job is created for a module, the job's dependencies contain
603 * both the required module and all its recursive dependencies.
608 * 'dependencies': [ module names ],
609 * 'ready': Function callback
610 * 'error': Function callback
613 * @property {Object[]} jobs
618 // For #requestPropagation() and #doPropagation()
619 willPropagate
= false,
624 * @property {Array} baseModules
626 baseModules
= $VARS
.baseModules
,
629 * For #addEmbeddedCSS() and #addLink()
632 * @property {HTMLElement|null} marker
634 marker
= document
.querySelector( 'meta[name="ResourceLoaderDynamicStyles"]' ),
636 // For #addEmbeddedCSS()
638 rAF
= window
.requestAnimationFrame
|| setTimeout
;
641 * Create a new style element and add it to the DOM.
644 * @param {string} text CSS text
645 * @param {Node|null} [nextNode] The element where the style tag
646 * should be inserted before
647 * @return {HTMLElement} Reference to the created style element
649 function newStyleTag( text
, nextNode
) {
650 var el
= document
.createElement( 'style' );
651 el
.appendChild( document
.createTextNode( text
) );
652 if ( nextNode
&& nextNode
.parentNode
) {
653 nextNode
.parentNode
.insertBefore( el
, nextNode
);
655 document
.head
.appendChild( el
);
662 * @param {Object} cssBuffer
664 function flushCssBuffer( cssBuffer
) {
666 // Mark this object as inactive now so that further calls to addEmbeddedCSS() from
667 // the callbacks go to a new buffer instead of this one (T105973)
668 cssBuffer
.active
= false;
669 newStyleTag( cssBuffer
.cssText
, marker
);
670 for ( i
= 0; i
< cssBuffer
.callbacks
.length
; i
++ ) {
671 cssBuffer
.callbacks
[ i
]();
676 * Add a bit of CSS text to the current browser page.
678 * The creation and insertion of the `<style>` element is debounced for two reasons:
680 * - Performing the insertion before the next paint round via requestAnimationFrame
681 * avoids forced or wasted style recomputations, which are expensive in browsers.
682 * - Reduce how often new stylesheets are inserted by letting additional calls to this
683 * function accumulate into a buffer for at least one JavaScript tick. Modules are
684 * received from the server in batches, which means there is likely going to be many
685 * calls to this function in a row within the same tick / the same call stack.
689 * @param {string} cssText CSS text to be added in a `<style>` tag.
690 * @param {Function} callback Called after the insertion has occurred
692 function addEmbeddedCSS( cssText
, callback
) {
693 // Create a buffer if:
694 // - We don't have one yet.
695 // - The previous one is closed.
696 // - The next CSS chunk syntactically needs to be at the start of a stylesheet (T37562).
697 if ( !nextCssBuffer
|| nextCssBuffer
.active
=== false || cssText
.slice( 0, '@import'.length
) === '@import' ) {
705 // Linebreak for somewhat distinguishable sections
706 nextCssBuffer
.cssText
+= '\n' + cssText
;
707 nextCssBuffer
.callbacks
.push( callback
);
709 if ( nextCssBuffer
.active
=== null ) {
710 nextCssBuffer
.active
= true;
711 // The flushCssBuffer callback has its parameter bound by reference, which means
712 // 1) We can still extend the buffer from our object reference after this point.
713 // 2) We can safely re-assign the variable (not the object) to start a new buffer.
714 rAF( flushCssBuffer
.bind( null, nextCssBuffer
) );
720 * @param {Array} modules List of module names
721 * @return {string} Hash of concatenated version hashes.
723 function getCombinedVersion( modules
) {
724 var hashes
= modules
.reduce( function ( result
, module
) {
725 return result
+ registry
[ module
].version
;
727 return fnv132( hashes
);
731 * Determine whether all dependencies are in state 'ready', which means we may
732 * execute the module or job now.
735 * @param {Array} modules Names of modules to be checked
736 * @return {boolean} True if all modules are in state 'ready', false otherwise
738 function allReady( modules
) {
740 for ( ; i
< modules
.length
; i
++ ) {
741 if ( mw
.loader
.getState( modules
[ i
] ) !== 'ready' ) {
749 * Determine whether all direct and base dependencies are in state 'ready'
752 * @param {string} module Name of the module to be checked
753 * @return {boolean} True if all direct/base dependencies are in state 'ready'; false otherwise
755 function allWithImplicitReady( module
) {
756 return allReady( registry
[ module
].dependencies
) &&
757 ( baseModules
.indexOf( module
) !== -1 || allReady( baseModules
) );
761 * Determine whether all dependencies are in state 'ready', which means we may
762 * execute the module or job now.
765 * @param {Array} modules Names of modules to be checked
766 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
768 function anyFailed( modules
) {
771 for ( ; i
< modules
.length
; i
++ ) {
772 state
= mw
.loader
.getState( modules
[ i
] );
773 if ( state
=== 'error' || state
=== 'missing' ) {
781 * Handle propagation of module state changes and reactions to them.
783 * - When a module reaches a failure state, this should be propagated to
784 * modules that depend on the failed module.
785 * - When a module reaches a final state, pending job callbacks for the
786 * module from mw.loader.using() should be called.
787 * - When a module reaches the 'ready' state from #execute(), consider
788 * executing dependant modules now having their dependencies satisfied.
789 * - When a module reaches the 'loaded' state from mw.loader.implement,
790 * consider executing it, if it has no unsatisfied dependencies.
794 function doPropagation() {
795 var errorModule
, baseModuleError
, module
, i
, failed
, job
,
798 // Keep going until the last iteration performed no actions.
800 didPropagate
= false;
802 // Stage 1: Propagate failures
803 while ( errorModules
.length
) {
804 errorModule
= errorModules
.shift();
805 baseModuleError
= baseModules
.indexOf( errorModule
) !== -1;
806 for ( module
in registry
) {
807 if ( registry
[ module
].state
!== 'error' && registry
[ module
].state
!== 'missing' ) {
808 if ( baseModuleError
&& baseModules
.indexOf( module
) === -1 ) {
809 // Propate error from base module to all regular (non-base) modules
810 registry
[ module
].state
= 'error';
812 } else if ( registry
[ module
].dependencies
.indexOf( errorModule
) !== -1 ) {
813 // Propagate error from dependency to depending module
814 registry
[ module
].state
= 'error';
815 // .. and propagate it further
816 errorModules
.push( module
);
823 // Stage 2: Execute 'loaded' modules with no unsatisfied dependencies
824 for ( module
in registry
) {
825 if ( registry
[ module
].state
=== 'loaded' && allWithImplicitReady( module
) ) {
826 // Recursively execute all dependent modules that were already loaded
827 // (waiting for execution) and no longer have unsatisfied dependencies.
828 // Base modules may have dependencies amongst eachother to ensure correct
829 // execution order. Regular modules wait for all base modules.
830 // eslint-disable-next-line no-use-before-define
836 // Stage 3: Invoke job callbacks that are no longer blocked
837 for ( i
= 0; i
< jobs
.length
; i
++ ) {
839 failed
= anyFailed( job
.dependencies
);
840 if ( failed
|| allReady( job
.dependencies
) ) {
844 if ( failed
&& job
.error
) {
845 job
.error( new Error( 'Failed dependencies' ), job
.dependencies
);
846 } else if ( !failed
&& job
.ready
) {
850 // A user-defined callback raised an exception.
851 // Swallow it to protect our state machine!
852 mw
.trackError( 'resourceloader.exception', {
854 source
: 'load-callback'
860 } while ( didPropagate
);
862 willPropagate
= false;
866 * Request a (debounced) call to doPropagation().
870 function requestPropagation() {
871 if ( willPropagate
) {
872 // Already scheduled, or, we're already in a doPropagation stack.
875 willPropagate
= true;
876 // Yield for two reasons:
877 // * Allow successive calls to mw.loader.implement() from the same
878 // load.php response, or from the same asyncEval() to be in the
879 // propagation batch.
880 // * Allow the browser to breathe between the reception of
881 // module source code and the execution of it.
883 // Use a high priority because the user may be waiting for interactions
884 // to start being possible. But, first provide a moment (up to 'timeout')
885 // for native input event handling (e.g. scrolling/typing/clicking).
886 mw
.requestIdleCallback( doPropagation
, { timeout
: 1 } );
890 * Update a module's state in the registry and make sure any neccesary
891 * propagation will occur. See #doPropagation for more about propagation.
892 * See #registry for more about how states are used.
895 * @param {string} module
896 * @param {string} state
898 function setAndPropagate( module
, state
) {
899 registry
[ module
].state
= state
;
900 if ( state
=== 'loaded' || state
=== 'ready' || state
=== 'error' || state
=== 'missing' ) {
901 if ( state
=== 'ready' ) {
902 // Queue to later be synced to the local module store.
903 mw
.loader
.store
.add( module
);
904 } else if ( state
=== 'error' || state
=== 'missing' ) {
905 errorModules
.push( module
);
907 requestPropagation();
912 * Resolve dependencies and detect circular references.
915 * @param {string} module Name of the top-level module whose dependencies shall be
916 * resolved and sorted.
917 * @param {Array} resolved Returns a topological sort of the given module and its
918 * dependencies, such that later modules depend on earlier modules. The array
919 * contains the module names. If the array contains already some module names,
920 * this function appends its result to the pre-existing array.
921 * @param {StringSet} [unresolved] Used to track the current dependency
922 * chain, and to report loops in the dependency graph.
923 * @throws {Error} If any unregistered module or a dependency loop is encountered
925 function sortDependencies( module
, resolved
, unresolved
) {
928 if ( !( module
in registry
) ) {
929 throw new Error( 'Unknown dependency: ' + module
);
932 if ( registry
[ module
].skip
!== null ) {
933 // eslint-disable-next-line no-new-func
934 skip
= new Function( registry
[ module
].skip
);
935 registry
[ module
].skip
= null;
937 registry
[ module
].skipped
= true;
938 registry
[ module
].dependencies
= [];
939 setAndPropagate( module
, 'ready' );
944 if ( resolved
.indexOf( module
) !== -1 ) {
945 // Module already resolved; nothing to do
948 // Create unresolved if not passed in
950 unresolved
= new StringSet();
954 if ( baseModules
.indexOf( module
) === -1 ) {
955 for ( i
= 0; i
< baseModules
.length
; i
++ ) {
956 if ( resolved
.indexOf( baseModules
[ i
] ) === -1 ) {
957 resolved
.push( baseModules
[ i
] );
962 // Tracks down dependencies
963 deps
= registry
[ module
].dependencies
;
964 unresolved
.add( module
);
965 for ( i
= 0; i
< deps
.length
; i
++ ) {
966 if ( resolved
.indexOf( deps
[ i
] ) === -1 ) {
967 if ( unresolved
.has( deps
[ i
] ) ) {
969 'Circular reference detected: ' + module
+ ' -> ' + deps
[ i
]
973 sortDependencies( deps
[ i
], resolved
, unresolved
);
976 resolved
.push( module
);
980 * Get names of module that a module depends on, in their proper dependency order.
983 * @param {string[]} modules Array of string module names
984 * @return {Array} List of dependencies, including 'module'.
985 * @throws {Error} If an unregistered module or a dependency loop is encountered
987 function resolve( modules
) {
990 for ( ; i
< modules
.length
; i
++ ) {
991 sortDependencies( modules
[ i
], resolved
);
997 * Like #resolve(), except it will silently ignore modules that
998 * are missing or have missing dependencies.
1001 * @param {string[]} modules Array of string module names
1002 * @return {Array} List of dependencies.
1004 function resolveStubbornly( modules
) {
1008 for ( ; i
< modules
.length
; i
++ ) {
1009 saved
= resolved
.slice();
1011 sortDependencies( modules
[ i
], resolved
);
1013 // This module is unknown or has unknown dependencies.
1014 // Undo any incomplete resolutions made and keep going.
1016 mw
.trackError( 'resourceloader.exception', {
1026 * Resolve a relative file path.
1028 * For example, resolveRelativePath( '../foo.js', 'resources/src/bar/bar.js' )
1029 * returns 'resources/src/foo.js'.
1031 * @param {string} relativePath Relative file path, starting with ./ or ../
1032 * @param {string} basePath Path of the file (not directory) relativePath is relative to
1033 * @return {string|null} Resolved path, or null if relativePath does not start with ./ or ../
1035 function resolveRelativePath( relativePath
, basePath
) {
1036 var prefixes
, prefix
, baseDirParts
,
1037 relParts
= relativePath
.match( /^((?:\.\.?\/)+)(.*)$/ );
1043 baseDirParts
= basePath
.split( '/' );
1044 // basePath looks like 'foo/bar/baz.js', so baseDirParts looks like [ 'foo', 'bar, 'baz.js' ]
1045 // Remove the file component at the end, so that we are left with only the directory path
1048 prefixes
= relParts
[ 1 ].split( '/' );
1049 // relParts[ 1 ] looks like '../../', so prefixes looks like [ '..', '..', '' ]
1050 // Remove the empty element at the end
1053 // For every ../ in the path prefix, remove one directory level from baseDirParts
1054 while ( ( prefix
= prefixes
.pop() ) !== undefined ) {
1055 if ( prefix
=== '..' ) {
1060 // If there's anything left of the base path, prepend it to the file path
1061 return ( baseDirParts
.length
? baseDirParts
.join( '/' ) + '/' : '' ) + relParts
[ 2 ];
1065 * Make a require() function scoped to a package file
1067 * @param {Object} moduleObj Module object from the registry
1068 * @param {string} basePath Path of the file this is scoped to. Used for relative paths.
1069 * @return {Function}
1071 function makeRequireFunction( moduleObj
, basePath
) {
1072 return function require( moduleName
) {
1073 var fileName
, fileContent
, result
, moduleParam
,
1074 scriptFiles
= moduleObj
.script
.files
;
1075 fileName
= resolveRelativePath( moduleName
, basePath
);
1076 if ( fileName
=== null ) {
1077 // Not a relative path, so it's a module name
1078 return mw
.loader
.require( moduleName
);
1081 if ( !hasOwn
.call( scriptFiles
, fileName
) ) {
1082 throw new Error( 'Cannot require() undefined file ' + fileName
);
1084 if ( hasOwn
.call( moduleObj
.packageExports
, fileName
) ) {
1085 // File has already been executed, return the cached result
1086 return moduleObj
.packageExports
[ fileName
];
1089 fileContent
= scriptFiles
[ fileName
];
1090 if ( typeof fileContent
=== 'function' ) {
1091 moduleParam
= { exports
: {} };
1092 fileContent( makeRequireFunction( moduleObj
, fileName
), moduleParam
);
1093 result
= moduleParam
.exports
;
1095 // fileContent is raw data, just pass it through
1096 result
= fileContent
;
1098 moduleObj
.packageExports
[ fileName
] = result
;
1104 * Load and execute a script.
1107 * @param {string} src URL to script, will be used as the src attribute in the script tag
1108 * @param {Function} [callback] Callback to run after request resolution
1110 function addScript( src
, callback
) {
1111 // Use a <script> element rather than XHR. Using XHR changes the request
1112 // headers (potentially missing a cache hit), and reduces caching in general
1113 // since browsers cache XHR much less (if at all). And XHR means we retrieve
1114 // text, so we'd need to eval, which then messes up line numbers.
1115 // The drawback is that <script> does not offer progress events, feedback is
1116 // only given after downloading, parsing, and execution have completed.
1117 var script
= document
.createElement( 'script' );
1119 script
.onload
= script
.onerror = function () {
1120 if ( script
.parentNode
) {
1121 script
.parentNode
.removeChild( script
);
1129 document
.head
.appendChild( script
);
1133 * Queue the loading and execution of a script for a particular module.
1135 * This does for debug mode what runScript() does for production.
1138 * @param {string} src URL of the script
1139 * @param {string} moduleName Name of currently executing module
1140 * @param {Function} callback Callback to run after addScript() resolution
1142 function queueModuleScript( src
, moduleName
, callback
) {
1143 pendingRequests
.push( function () {
1144 // Keep in sync with execute()/runScript().
1145 if ( moduleName
!== 'jquery' ) {
1146 window
.require
= mw
.loader
.require
;
1147 window
.module
= registry
[ moduleName
].module
;
1149 addScript( src
, function () {
1150 // 'module.exports' should not persist after the file is executed to
1151 // avoid leakage to unrelated code. 'require' should be kept, however,
1152 // as asynchronous access to 'require' is allowed and expected. (T144879)
1153 delete window
.module
;
1155 // Start the next one (if any)
1156 if ( pendingRequests
[ 0 ] ) {
1157 pendingRequests
.shift()();
1159 handlingPendingRequests
= false;
1163 if ( !handlingPendingRequests
&& pendingRequests
[ 0 ] ) {
1164 handlingPendingRequests
= true;
1165 pendingRequests
.shift()();
1170 * Utility function for execute()
1173 * @param {string} [media] Media attribute
1174 * @param {string} url URL
1176 function addLink( media
, url
) {
1177 var el
= document
.createElement( 'link' );
1179 el
.rel
= 'stylesheet';
1180 if ( media
&& media
!== 'all' ) {
1183 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1184 // see #addEmbeddedCSS, T33676, T43331, and T49277 for details.
1187 if ( marker
&& marker
.parentNode
) {
1188 marker
.parentNode
.insertBefore( el
, marker
);
1190 document
.head
.appendChild( el
);
1196 * @param {string} code JavaScript code
1198 function domEval( code
) {
1199 var script
= document
.createElement( 'script' );
1200 if ( mw
.config
.get( 'wgCSPNonce' ) !== false ) {
1201 script
.nonce
= mw
.config
.get( 'wgCSPNonce' );
1204 document
.head
.appendChild( script
);
1205 script
.parentNode
.removeChild( script
);
1209 * Add one or more modules to the module load queue.
1214 * @param {string[]} dependencies Array of module names in the registry
1215 * @param {Function} [ready] Callback to execute when all dependencies are ready
1216 * @param {Function} [error] Callback to execute when any dependency fails
1218 function enqueue( dependencies
, ready
, error
) {
1219 if ( allReady( dependencies
) ) {
1220 // Run ready immediately
1221 if ( ready
!== undefined ) {
1227 if ( anyFailed( dependencies
) ) {
1228 if ( error
!== undefined ) {
1229 // Execute error immediately if any dependencies have errors
1231 new Error( 'One or more dependencies failed to load' ),
1238 // Not all dependencies are ready, add to the load queue...
1240 // Add ready and error callbacks if they were given
1241 if ( ready
!== undefined || error
!== undefined ) {
1243 // Narrow down the list to modules that are worth waiting for
1244 dependencies
: dependencies
.filter( function ( module
) {
1245 var state
= registry
[ module
].state
;
1246 return state
=== 'registered' || state
=== 'loaded' || state
=== 'loading' || state
=== 'executing';
1253 dependencies
.forEach( function ( module
) {
1254 // Only queue modules that are still in the initial 'registered' state
1255 // (not ones already loading, ready or error).
1256 if ( registry
[ module
].state
=== 'registered' && queue
.indexOf( module
) === -1 ) {
1257 // Private modules must be embedded in the page. Don't bother queuing
1258 // these as the server will deny them anyway (T101806).
1259 if ( registry
[ module
].group
=== 'private' ) {
1260 setAndPropagate( module
, 'error' );
1262 queue
.push( module
);
1271 * Executes a loaded module, making it ready to use
1274 * @param {string} module Module name to execute
1276 function execute( module
) {
1277 var key
, value
, media
, i
, urls
, cssHandle
, siteDeps
, siteDepErr
, runScript
,
1280 if ( registry
[ module
].state
!== 'loaded' ) {
1281 throw new Error( 'Module in state "' + registry
[ module
].state
+ '" may not be executed: ' + module
);
1284 registry
[ module
].state
= 'executing';
1285 $CODE
.profileExecuteStart();
1287 runScript = function () {
1288 var script
, markModuleReady
, nestedAddScript
, mainScript
;
1290 $CODE
.profileScriptStart();
1291 script
= registry
[ module
].script
;
1292 markModuleReady = function () {
1293 $CODE
.profileScriptEnd();
1294 setAndPropagate( module
, 'ready' );
1296 nestedAddScript = function ( arr
, callback
, i
) {
1297 // Recursively call queueModuleScript() in its own callback
1298 // for each element of arr.
1299 if ( i
>= arr
.length
) {
1300 // We're at the end of the array
1305 queueModuleScript( arr
[ i
], module
, function () {
1306 nestedAddScript( arr
, callback
, i
+ 1 );
1311 if ( Array
.isArray( script
) ) {
1312 nestedAddScript( script
, markModuleReady
, 0 );
1314 typeof script
=== 'function' || (
1315 typeof script
=== 'object' &&
1319 if ( typeof script
=== 'function' ) {
1320 // Keep in sync with queueModuleScript() for debug mode
1321 if ( module
=== 'jquery' ) {
1322 // This is a special case for when 'jquery' itself is being loaded.
1323 // - The standard jquery.js distribution does not set `window.jQuery`
1324 // in CommonJS-compatible environments (Node.js, AMD, RequireJS, etc.).
1325 // - MediaWiki's 'jquery' module also bundles jquery.migrate.js, which
1326 // in a CommonJS-compatible environment, will use require('jquery'),
1327 // but that can't work when we're still inside that module.
1330 // Pass jQuery twice so that the signature of the closure which wraps
1331 // the script can bind both '$' and 'jQuery'.
1332 script( window
.$, window
.$, mw
.loader
.require
, registry
[ module
].module
);
1335 mainScript
= script
.files
[ script
.main
];
1336 if ( typeof mainScript
!== 'function' ) {
1337 throw new Error( 'Main file ' + script
.main
+ ' in module ' + module
+
1338 ' must be of type function, found ' + typeof mainScript
);
1340 // jQuery parameters are not passed for multi-file modules
1342 makeRequireFunction( registry
[ module
], script
.main
),
1343 registry
[ module
].module
1347 } else if ( typeof script
=== 'string' ) {
1348 // Site and user modules are legacy scripts that run in the global scope.
1349 // This is transported as a string instead of a function to avoid needing
1350 // to use string manipulation to undo the function wrapper.
1355 // Module without script
1359 // Use mw.track instead of mw.log because these errors are common in production mode
1360 // (e.g. undefined variable), and mw.log is only enabled in debug mode.
1361 setAndPropagate( module
, 'error' );
1362 $CODE
.profileScriptEnd();
1363 mw
.trackError( 'resourceloader.exception', {
1366 source
: 'module-execute'
1371 // Add localizations to message system
1372 if ( registry
[ module
].messages
) {
1373 mw
.messages
.set( registry
[ module
].messages
);
1376 // Initialise templates
1377 if ( registry
[ module
].templates
) {
1378 mw
.templates
.set( module
, registry
[ module
].templates
);
1381 // Adding of stylesheets is asynchronous via addEmbeddedCSS().
1382 // The below function uses a counting semaphore to make sure we don't call
1383 // runScript() until after this module's stylesheets have been inserted
1385 cssHandle = function () {
1386 // Increase semaphore, when creating a callback for addEmbeddedCSS.
1388 return function () {
1390 // Decrease semaphore, when said callback is invoked.
1392 if ( cssPending
=== 0 ) {
1394 // This callback is exposed to addEmbeddedCSS, which is outside the execute()
1395 // function and is not concerned with state-machine integrity. In turn,
1396 // addEmbeddedCSS() actually exposes stuff further into the browser (rAF).
1397 // If increment and decrement callbacks happen in the wrong order, or start
1398 // again afterwards, then this branch could be reached multiple times.
1399 // To protect the integrity of the state-machine, prevent that from happening
1400 // by making runScript() cannot be called more than once. We store a private
1401 // reference when we first reach this branch, then deference the original, and
1402 // call our reference to it.
1403 runScriptCopy
= runScript
;
1404 runScript
= undefined;
1410 // Process styles (see also mw.loader.implement)
1411 // * back-compat: { <media>: css }
1412 // * back-compat: { <media>: [url, ..] }
1413 // * { "css": [css, ..] }
1414 // * { "url": { <media>: [url, ..] } }
1415 if ( registry
[ module
].style
) {
1416 for ( key
in registry
[ module
].style
) {
1417 value
= registry
[ module
].style
[ key
];
1420 if ( key
!== 'url' && key
!== 'css' ) {
1421 // Backwards compatibility, key is a media-type
1422 if ( typeof value
=== 'string' ) {
1423 // back-compat: { <media>: css }
1424 // Ignore 'media' because it isn't supported (nor was it used).
1425 // Strings are pre-wrapped in "@media". The media-type was just ""
1426 // (because it had to be set to something).
1427 // This is one of the reasons why this format is no longer used.
1428 addEmbeddedCSS( value
, cssHandle() );
1430 // back-compat: { <media>: [url, ..] }
1436 // Array of css strings in key 'css',
1437 // or back-compat array of urls from media-type
1438 if ( Array
.isArray( value
) ) {
1439 for ( i
= 0; i
< value
.length
; i
++ ) {
1440 if ( key
=== 'bc-url' ) {
1441 // back-compat: { <media>: [url, ..] }
1442 addLink( media
, value
[ i
] );
1443 } else if ( key
=== 'css' ) {
1444 // { "css": [css, ..] }
1445 addEmbeddedCSS( value
[ i
], cssHandle() );
1448 // Not an array, but a regular object
1449 // Array of urls inside media-type key
1450 } else if ( typeof value
=== 'object' ) {
1451 // { "url": { <media>: [url, ..] } }
1452 for ( media
in value
) {
1453 urls
= value
[ media
];
1454 for ( i
= 0; i
< urls
.length
; i
++ ) {
1455 addLink( media
, urls
[ i
] );
1462 // End profiling of execute()-self before we call runScript(),
1463 // which we want to measure separately without overlap.
1464 $CODE
.profileExecuteEnd();
1466 if ( module
=== 'user' ) {
1467 // Implicit dependency on the site module. Not a real dependency because it should
1468 // run after 'site' regardless of whether it succeeds or fails.
1469 // Note: This is a simplified version of mw.loader.using(), inlined here because
1470 // mw.loader.using() is part of mediawiki.base (depends on jQuery; T192623).
1472 siteDeps
= resolve( [ 'site' ] );
1477 if ( siteDepErr
=== undefined ) {
1478 enqueue( siteDeps
, runScript
, runScript
);
1480 } else if ( cssPending
=== 0 ) {
1481 // Regular module without styles
1484 // else: runScript will get called via cssHandle()
1487 function sortQuery( o
) {
1496 for ( key
= 0; key
< a
.length
; key
++ ) {
1497 sorted
[ a
[ key
] ] = o
[ a
[ key
] ];
1503 * Converts a module map of the form `{ foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }`
1504 * to a query string of the form `foo.bar,baz|bar.baz,quux`.
1506 * See `ResourceLoader::makePackedModulesString()` in PHP, of which this is a port.
1507 * On the server, unpacking is done by `ResourceLoaderContext::expandModuleNames()`.
1509 * Note: This is only half of the logic, the other half has to be in #batchRequest(),
1510 * because its implementation needs to keep track of potential string size in order
1511 * to decide when to split the requests due to url size.
1514 * @param {Object} moduleMap Module map
1516 * @return {string} return.str Module query string
1517 * @return {Array} return.list List of module names in matching order
1519 function buildModulesString( moduleMap
) {
1524 function restore( suffix
) {
1528 for ( prefix
in moduleMap
) {
1529 p
= prefix
=== '' ? '' : prefix
+ '.';
1530 str
.push( p
+ moduleMap
[ prefix
].join( ',' ) );
1531 list
.push
.apply( list
, moduleMap
[ prefix
].map( restore
) );
1534 str
: str
.join( '|' ),
1540 * Resolve indexed dependencies.
1542 * ResourceLoader uses an optimisation to save space which replaces module names in
1543 * dependency lists with the index of that module within the array of module
1544 * registration data if it exists. The benefit is a significant reduction in the data
1545 * size of the startup module. This function changes those dependency lists back to
1546 * arrays of strings.
1549 * @param {Array} modules Modules array
1551 function resolveIndexedDependencies( modules
) {
1553 function resolveIndex( dep
) {
1554 return typeof dep
=== 'number' ? modules
[ dep
][ 0 ] : dep
;
1556 for ( i
= 0; i
< modules
.length
; i
++ ) {
1557 deps
= modules
[ i
][ 2 ];
1559 for ( j
= 0; j
< deps
.length
; j
++ ) {
1560 deps
[ j
] = resolveIndex( deps
[ j
] );
1568 * @param {Object} params Map of parameter names to values
1571 function makeQueryString( params
) {
1572 return Object
.keys( params
).map( function ( key
) {
1573 return encodeURIComponent( key
) + '=' + encodeURIComponent( params
[ key
] );
1578 * Create network requests for a batch of modules.
1580 * This is an internal method for #work(). This must not be called directly
1581 * unless the modules are already registered, and no request is in progress,
1582 * and the module state has already been set to `loading`.
1585 * @param {string[]} batch
1587 function batchRequest( batch
) {
1588 var reqBase
, splits
, b
, bSource
, bGroup
,
1589 source
, group
, i
, modules
, sourceLoadScript
,
1590 currReqBase
, currReqBaseLength
, moduleMap
, currReqModules
, l
,
1591 lastDotIndex
, prefix
, suffix
, bytesAdded
;
1594 * Start the currently drafted request to the server.
1598 function doRequest() {
1599 // Optimisation: Inherit (Object.create), not copy ($.extend)
1600 var query
= Object
.create( currReqBase
),
1601 packed
= buildModulesString( moduleMap
);
1602 query
.modules
= packed
.str
;
1603 // The packing logic can change the effective order, even if the input was
1604 // sorted. As such, the call to getCombinedVersion() must use this
1605 // effective order, instead of currReqModules, as otherwise the combined
1606 // version will not match the hash expected by the server based on
1607 // combining versions from the module query string in-order. (T188076)
1608 query
.version
= getCombinedVersion( packed
.list
);
1609 query
= sortQuery( query
);
1610 addScript( sourceLoadScript
+ '?' + makeQueryString( query
) );
1613 if ( !batch
.length
) {
1617 // Always order modules alphabetically to help reduce cache
1618 // misses for otherwise identical content.
1621 // Query parameters common to all requests
1623 skin
: mw
.config
.get( 'skin' ),
1624 lang
: mw
.config
.get( 'wgUserLanguage' ),
1625 debug
: mw
.config
.get( 'debug' )
1628 // Split module list by source and by group.
1629 splits
= Object
.create( null );
1630 for ( b
= 0; b
< batch
.length
; b
++ ) {
1631 bSource
= registry
[ batch
[ b
] ].source
;
1632 bGroup
= registry
[ batch
[ b
] ].group
;
1633 if ( !splits
[ bSource
] ) {
1634 splits
[ bSource
] = Object
.create( null );
1636 if ( !splits
[ bSource
][ bGroup
] ) {
1637 splits
[ bSource
][ bGroup
] = [];
1639 splits
[ bSource
][ bGroup
].push( batch
[ b
] );
1642 for ( source
in splits
) {
1643 sourceLoadScript
= sources
[ source
];
1645 for ( group
in splits
[ source
] ) {
1647 // Cache access to currently selected list of
1648 // modules for this group from this source.
1649 modules
= splits
[ source
][ group
];
1651 // Query parameters common to requests for this module group
1652 // Optimisation: Inherit (Object.create), not copy ($.extend)
1653 currReqBase
= Object
.create( reqBase
);
1654 // User modules require a user name in the query string.
1655 if ( group
=== 'user' && mw
.config
.get( 'wgUserName' ) !== null ) {
1656 currReqBase
.user
= mw
.config
.get( 'wgUserName' );
1659 // In addition to currReqBase, doRequest() will also add 'modules' and 'version'.
1660 // > '&modules='.length === 9
1661 // > '&version=1234567'.length === 16
1663 currReqBaseLength
= makeQueryString( currReqBase
).length
+ 25;
1665 // We may need to split up the request to honor the query string length limit,
1666 // so build it piece by piece.
1667 l
= currReqBaseLength
;
1668 moduleMap
= Object
.create( null ); // { prefix: [ suffixes ] }
1669 currReqModules
= [];
1671 for ( i
= 0; i
< modules
.length
; i
++ ) {
1672 // Determine how many bytes this module would add to the query string
1673 lastDotIndex
= modules
[ i
].lastIndexOf( '.' );
1674 // If lastDotIndex is -1, substr() returns an empty string
1675 prefix
= modules
[ i
].substr( 0, lastDotIndex
);
1676 suffix
= modules
[ i
].slice( lastDotIndex
+ 1 );
1677 bytesAdded
= moduleMap
[ prefix
] ?
1678 suffix
.length
+ 3 : // '%2C'.length == 3
1679 modules
[ i
].length
+ 3; // '%7C'.length == 3
1681 // If the url would become too long, create a new one, but don't create empty requests
1682 if ( currReqModules
.length
&& l
+ bytesAdded
> mw
.loader
.maxQueryLength
) {
1683 // Dispatch what we've got...
1685 // .. and start again.
1686 l
= currReqBaseLength
;
1687 moduleMap
= Object
.create( null );
1688 currReqModules
= [];
1690 mw
.track( 'resourceloader.splitRequest', { maxQueryLength
: mw
.loader
.maxQueryLength
} );
1692 if ( !moduleMap
[ prefix
] ) {
1693 moduleMap
[ prefix
] = [];
1696 moduleMap
[ prefix
].push( suffix
);
1697 currReqModules
.push( modules
[ i
] );
1699 // If there's anything left in moduleMap, request that too
1700 if ( currReqModules
.length
) {
1709 * @param {string[]} implementations Array containing pieces of JavaScript code in the
1710 * form of calls to mw.loader#implement().
1711 * @param {Function} cb Callback in case of failure
1712 * @param {Error} cb.err
1714 function asyncEval( implementations
, cb
) {
1715 if ( !implementations
.length
) {
1718 mw
.requestIdleCallback( function () {
1720 domEval( implementations
.join( ';' ) );
1728 * Make a versioned key for a specific module.
1731 * @param {string} module Module name
1732 * @return {string|null} Module key in format '`[name]@[version]`',
1733 * or null if the module does not exist
1735 function getModuleKey( module
) {
1736 return module
in registry
? ( module
+ '@' + registry
[ module
].version
) : null;
1741 * @param {string} key Module name or '`[name]@[version]`'
1744 function splitModuleKey( key
) {
1745 var index
= key
.indexOf( '@' );
1746 if ( index
=== -1 ) {
1753 name
: key
.slice( 0, index
),
1754 version
: key
.slice( index
+ 1 )
1760 * @param {string} module
1761 * @param {string|number} [version]
1762 * @param {string[]} [dependencies]
1763 * @param {string} [group]
1764 * @param {string} [source]
1765 * @param {string} [skip]
1767 function registerOne( module
, version
, dependencies
, group
, source
, skip
) {
1768 if ( module
in registry
) {
1769 throw new Error( 'module already registered: ' + module
);
1771 registry
[ module
] = {
1772 // Exposed to execute() for mw.loader.implement() closures.
1773 // Import happens via require().
1777 // module.export objects for each package file inside this module
1779 version
: String( version
|| '' ),
1780 dependencies
: dependencies
|| [],
1781 group
: typeof group
=== 'string' ? group
: null,
1782 source
: typeof source
=== 'string' ? source
: 'local',
1783 state
: 'registered',
1784 skip
: typeof skip
=== 'string' ? skip
: null
1788 /* Public Members */
1791 * The module registry is exposed as an aid for debugging and inspecting page
1792 * state; it is not a public interface for modifying the registry.
1798 moduleRegistry
: registry
,
1801 * Exposed for testing and debugging only.
1803 * @see #batchRequest
1807 maxQueryLength
: $VARS
.maxQueryLength
,
1810 * @inheritdoc #newStyleTag
1813 addStyleTag
: newStyleTag
,
1820 * Start loading of all queued module dependencies.
1825 var implementations
, sourceModules
,
1829 // Appends a list of modules from the queue to the batch
1830 for ( ; q
< queue
.length
; q
++ ) {
1831 // Only load modules which are registered
1832 if ( queue
[ q
] in registry
&& registry
[ queue
[ q
] ].state
=== 'registered' ) {
1833 // Prevent duplicate entries
1834 if ( batch
.indexOf( queue
[ q
] ) === -1 ) {
1835 batch
.push( queue
[ q
] );
1836 // Mark registered modules as loading
1837 registry
[ queue
[ q
] ].state
= 'loading';
1842 // Now that the queue has been processed into a batch, clear the queue.
1843 // This MUST happen before we initiate any eval or network request. Otherwise,
1844 // it is possible for a cached script to instantly trigger the same work queue
1845 // again; all before we've cleared it causing each request to include modules
1846 // which are already loaded.
1849 if ( !batch
.length
) {
1853 mw
.loader
.store
.init();
1854 if ( mw
.loader
.store
.enabled
) {
1855 implementations
= [];
1857 batch
= batch
.filter( function ( module
) {
1858 var implementation
= mw
.loader
.store
.get( module
);
1859 if ( implementation
) {
1860 implementations
.push( implementation
);
1861 sourceModules
.push( module
);
1866 asyncEval( implementations
, function ( err
) {
1868 // Not good, the cached mw.loader.implement calls failed! This should
1869 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1870 // Depending on how corrupt the string is, it is likely that some
1871 // modules' implement() succeeded while the ones after the error will
1872 // never run and leave their modules in the 'loading' state forever.
1873 mw
.loader
.store
.stats
.failed
++;
1875 // Since this is an error not caused by an individual module but by
1876 // something that infected the implement call itself, don't take any
1877 // risks and clear everything in this cache.
1878 mw
.loader
.store
.clear();
1880 mw
.trackError( 'resourceloader.exception', {
1882 source
: 'store-eval'
1884 // Re-add the failed ones that are still pending back to the batch
1885 failed
= sourceModules
.filter( function ( module
) {
1886 return registry
[ module
].state
=== 'loading';
1888 batchRequest( failed
);
1892 batchRequest( batch
);
1896 * Register a source.
1898 * The #work() method will use this information to split up requests by source.
1900 * mw.loader.addSource( { mediawikiwiki: 'https://www.mediawiki.org/w/load.php' } );
1903 * @param {Object} ids An object mapping ids to load.php end point urls
1904 * @throws {Error} If source id is already registered
1906 addSource: function ( ids
) {
1909 if ( id
in sources
) {
1910 throw new Error( 'source already registered: ' + id
);
1912 sources
[ id
] = ids
[ id
];
1917 * Register a module, letting the system know about it and its properties.
1919 * The startup module calls this method.
1921 * When using multiple module registration by passing an array, dependencies that
1922 * are specified as references to modules within the array will be resolved before
1923 * the modules are registered.
1925 * @param {string|Array} modules Module name or array of arrays, each containing
1926 * a list of arguments compatible with this method
1927 * @param {string|number} [version] Module version hash (falls backs to empty string)
1928 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1929 * @param {string[]} [dependencies] Array of module names on which this module depends.
1930 * @param {string} [group=null] Group which the module is in
1931 * @param {string} [source='local'] Name of the source
1932 * @param {string} [skip=null] Script body of the skip function
1934 register: function ( modules
) {
1936 if ( typeof modules
=== 'object' ) {
1937 resolveIndexedDependencies( modules
);
1938 // Optimisation: Up to 55% faster.
1939 // Typically called only once, and with a batch.
1940 // See <https://gist.github.com/Krinkle/f06fdb3de62824c6c16f02a0e6ce0e66>
1941 // Benchmarks taught us that the code for adding an object to `registry`
1942 // should actually be inline, or in a simple function that does no
1943 // arguments manipulation, and isn't also the caller itself.
1944 // JS semantics make it hard to optimise recursion to a different
1945 // signature of itself.
1946 for ( i
= 0; i
< modules
.length
; i
++ ) {
1947 registerOne
.apply( null, modules
[ i
] );
1950 registerOne
.apply( null, arguments
);
1955 * Implement a module given the components that make up the module.
1957 * When #load() or #using() requests one or more modules, the server
1958 * response contain calls to this function.
1960 * @param {string} module Name of module and current module version. Formatted
1961 * as '`[name]@[version]`". This version should match the requested version
1962 * (from #batchRequest and #registry). This avoids race conditions (T117587).
1963 * For back-compat with MediaWiki 1.27 and earlier, the version may be omitted.
1964 * @param {Function|Array|string|Object} [script] Module code. This can be a function,
1965 * a list of URLs to load via `<script src>`, a string for `$.globalEval()`, or an
1966 * object like {"files": {"foo.js":function, "bar.js": function, ...}, "main": "foo.js"}.
1967 * If an object is provided, the main file will be executed immediately, and the other
1968 * files will only be executed if loaded via require(). If a function or string is
1969 * provided, it will be executed/evaluated immediately. If an array is provided, all
1970 * URLs in the array will be loaded immediately, and executed as soon as they arrive.
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 ( !( name
in registry
) ) {
1994 mw
.loader
.register( name
);
1996 // Check for duplicate implementation
1997 if ( 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 setAndPropagate( name
, 'loaded' );
2019 * Load an external script or one or more modules.
2021 * This method takes a list of unrelated modules. Use cases:
2023 * - A web page will be composed of many different widgets. These widgets independently
2024 * queue their ResourceLoader modules (`OutputPage::addModules()`). If any of them
2025 * have problems, or are no longer known (e.g. cached HTML), the other modules
2026 * should still be loaded.
2027 * - This method is used for preloading, which must not throw. Later code that
2028 * calls #using() will handle the error.
2030 * @param {string|Array} modules Either the name of a module, array of modules,
2031 * or a URL of an external script or style
2032 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
2033 * external script or style; acceptable values are "text/css" and
2034 * "text/javascript"; if no type is provided, text/javascript is assumed.
2036 load: function ( modules
, type
) {
2039 // Allow calling with a url or single dependency as a string
2040 if ( typeof modules
=== 'string' ) {
2041 // "https://example.org/x.js", "http://example.org/x.js", "//example.org/x.js", "/x.js"
2042 if ( /^(https?:)?\/?\//.test( modules
) ) {
2043 if ( type
=== 'text/css' ) {
2044 l
= document
.createElement( 'link' );
2045 l
.rel
= 'stylesheet';
2047 document
.head
.appendChild( l
);
2050 if ( type
=== 'text/javascript' || type
=== undefined ) {
2051 addScript( modules
);
2055 throw new Error( 'type must be text/css or text/javascript, found ' + type
);
2057 // Called with single module
2058 modules
= [ modules
];
2061 // Filter out top-level modules that are unknown or failed to load before.
2062 filtered
= modules
.filter( function ( module
) {
2063 var state
= mw
.loader
.getState( module
);
2064 return state
!== 'error' && state
!== 'missing';
2066 // Resolve remaining list using the known dependency tree.
2067 // This also filters out modules with unknown dependencies. (T36853)
2068 filtered
= resolveStubbornly( filtered
);
2069 // Some modules are not yet ready, add to module load queue.
2070 enqueue( filtered
, undefined, undefined );
2074 * Change the state of one or more modules.
2076 * @param {Object} states Object of module name/state pairs
2078 state: function ( states
) {
2080 for ( module
in states
) {
2081 state
= states
[ module
];
2082 if ( !( module
in registry
) ) {
2083 mw
.loader
.register( module
);
2085 setAndPropagate( module
, state
);
2090 * Get the version of a module.
2092 * @param {string} module Name of module
2093 * @return {string|null} The version, or null if the module (or its version) is not
2096 getVersion: function ( module
) {
2097 return module
in registry
? registry
[ module
].version
: null;
2101 * Get the state of a module.
2103 * @param {string} module Name of module
2104 * @return {string|null} The state, or null if the module (or its state) is not
2107 getState: function ( module
) {
2108 return module
in registry
? registry
[ module
].state
: null;
2112 * Get the names of all registered modules.
2116 getModuleNames: function () {
2117 return Object
.keys( registry
);
2121 * Get the exported value of a module.
2123 * This static method is publicly exposed for debugging purposes
2124 * only and must not be used in production code. In production code,
2125 * please use the dynamically provided `require()` function instead.
2127 * In case of lazy-loaded modules via mw.loader#using(), the returned
2128 * Promise provides the function, see #using() for examples.
2132 * @param {string} moduleName Module name
2133 * @return {Mixed} Exported value
2135 require: function ( moduleName
) {
2136 var state
= mw
.loader
.getState( moduleName
);
2138 // Only ready modules can be required
2139 if ( state
!== 'ready' ) {
2140 // Module may've forgotten to declare a dependency
2141 throw new Error( 'Module "' + moduleName
+ '" is not loaded' );
2144 return registry
[ moduleName
].module
.exports
;
2148 * On browsers that implement the localStorage API, the module store serves as a
2149 * smart complement to the browser cache. Unlike the browser cache, the module store
2150 * can slice a concatenated response from ResourceLoader into its constituent
2151 * modules and cache each of them separately, using each module's versioning scheme
2152 * to determine when the cache should be invalidated.
2156 * @class mw.loader.store
2159 // Whether the store is in use on this page.
2162 // Modules whose string representation exceeds 100 kB are
2163 // ineligible for storage. See bug T66721.
2164 MODULE_SIZE_MAX
: 100 * 1000,
2166 // The contents of the store, mapping '[name]@[version]' keys
2167 // to module implementations.
2170 // Names of modules to be stored during the next update.
2171 // See add() and update().
2175 stats
: { hits
: 0, misses
: 0, expired
: 0, failed
: 0 },
2178 * Construct a JSON-serializable object representing the content of the store.
2180 * @return {Object} Module store contents.
2182 toJSON: function () {
2183 return { items
: mw
.loader
.store
.items
, vary
: mw
.loader
.store
.getVary() };
2187 * Get the localStorage key for the entire module store. The key references
2188 * $wgDBname to prevent clashes between wikis which share a common host.
2190 * @return {string} localStorage item key
2192 getStoreKey: function () {
2193 return 'MediaWikiModuleStore:' + mw
.config
.get( 'wgDBname' );
2197 * Get a key on which to vary the module cache.
2199 * @return {string} String of concatenated vary conditions.
2201 getVary: function () {
2202 return mw
.config
.get( 'skin' ) + ':' +
2203 mw
.config
.get( 'wgResourceLoaderStorageVersion' ) + ':' +
2204 mw
.config
.get( 'wgUserLanguage' );
2208 * Initialize the store.
2210 * Retrieves store from localStorage and (if successfully retrieved) decoding
2211 * the stored JSON value to a plain object.
2213 * The try / catch block is used for JSON & localStorage feature detection.
2214 * See the in-line documentation for Modernizr's localStorage feature detection
2215 * code for a full account of why we need a try / catch:
2216 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2221 if ( this.enabled
!== null ) {
2227 // Disabled because localStorage quotas are tight and (in Firefox's case)
2228 // shared by multiple origins.
2229 // See T66721, and <https://bugzilla.mozilla.org/show_bug.cgi?id=1064466>.
2230 /Firefox/.test( navigator
.userAgent
) ||
2232 // Disabled by configuration.
2233 !mw
.config
.get( 'wgResourceLoaderStorageEnabled' )
2235 // Clear any previous store to free up space. (T66721)
2237 this.enabled
= false;
2240 if ( mw
.config
.get( 'debug' ) ) {
2241 // Disable module store in debug mode
2242 this.enabled
= false;
2247 // This a string we stored, or `null` if the key does not (yet) exist.
2248 raw
= localStorage
.getItem( this.getStoreKey() );
2249 // If we get here, localStorage is available; mark enabled
2250 this.enabled
= true;
2251 // If null, JSON.parse() will cast to string and re-parse, still null.
2252 data
= JSON
.parse( raw
);
2253 if ( data
&& typeof data
.items
=== 'object' && data
.vary
=== this.getVary() ) {
2254 this.items
= data
.items
;
2258 // Perhaps localStorage was disabled by the user, or got corrupted.
2259 // See point 3 and 4 below. (T195647)
2262 // If we get here, one of four things happened:
2264 // 1. localStorage did not contain our store key.
2265 // This means `raw` is `null`, and we're on a fresh page view (cold cache).
2266 // The store was enabled, and `items` starts fresh.
2268 // 2. localStorage contained parseable data under our store key,
2269 // but it's not applicable to our current context (see getVary).
2270 // The store was enabled, and `items` starts fresh.
2272 // 3. JSON.parse threw (localStorage contained corrupt data).
2273 // This means `raw` contains a string.
2274 // The store was enabled, and `items` starts fresh.
2276 // 4. localStorage threw (disabled or otherwise unavailable).
2277 // This means `raw` was never assigned.
2278 // We will disable the store below.
2279 if ( raw
=== undefined ) {
2280 // localStorage failed; disable store
2281 this.enabled
= false;
2286 * Retrieve a module from the store and update cache hit stats.
2288 * @param {string} module Module name
2289 * @return {string|boolean} Module implementation or false if unavailable
2291 get: function ( module
) {
2294 if ( !this.enabled
) {
2298 key
= getModuleKey( module
);
2299 if ( key
in this.items
) {
2301 return this.items
[ key
];
2304 this.stats
.misses
++;
2309 * Queue the name of a module that the next update should consider storing.
2312 * @param {string} module Module name
2314 add: function ( module
) {
2315 if ( !this.enabled
) {
2318 this.queue
.push( module
);
2319 this.requestUpdate();
2323 * Add the contents of the named module to the in-memory store.
2325 * This method does not guarantee that the module will be stored.
2326 * Inspection of the module's meta data and size will ultimately decide that.
2328 * This method is considered internal to mw.loader.store and must only
2329 * be called if the store is enabled.
2332 * @param {string} module Module name
2334 set: function ( module
) {
2337 descriptor
= mw
.loader
.moduleRegistry
[ module
];
2339 key
= getModuleKey( module
);
2342 // Already stored a copy of this exact version
2343 key
in this.items
||
2344 // Module failed to load
2346 descriptor
.state
!== 'ready' ||
2347 // Unversioned, private, or site-/user-specific
2348 !descriptor
.version
||
2349 descriptor
.group
=== 'private' ||
2350 descriptor
.group
=== 'user' ||
2351 // Partial descriptor
2352 // (e.g. skipped module, or style module with state=ready)
2353 [ descriptor
.script
, descriptor
.style
, descriptor
.messages
,
2354 descriptor
.templates
].indexOf( undefined ) !== -1
2361 if ( typeof descriptor
.script
=== 'function' ) {
2362 // Function literal: cast to string
2363 encodedScript
= String( descriptor
.script
);
2365 // Plain object: serialise as object literal (not JSON),
2366 // making sure to preserve the functions.
2367 typeof descriptor
.script
=== 'object' &&
2368 descriptor
.script
&&
2369 !Array
.isArray( descriptor
.script
)
2371 encodedScript
= '{' +
2372 'main:' + JSON
.stringify( descriptor
.script
.main
) + ',' +
2374 Object
.keys( descriptor
.script
.files
).map( function ( key
) {
2375 var value
= descriptor
.script
.files
[ key
];
2376 return JSON
.stringify( key
) + ':' +
2377 ( typeof value
=== 'function' ? value
: JSON
.stringify( value
) );
2381 // Array of urls, or null.
2382 encodedScript
= JSON
.stringify( descriptor
.script
);
2385 JSON
.stringify( key
),
2387 JSON
.stringify( descriptor
.style
),
2388 JSON
.stringify( descriptor
.messages
),
2389 JSON
.stringify( descriptor
.templates
)
2392 mw
.trackError( 'resourceloader.exception', {
2394 source
: 'store-localstorage-json'
2399 src
= 'mw.loader.implement(' + args
.join( ',' ) + ');';
2400 if ( src
.length
> this.MODULE_SIZE_MAX
) {
2403 this.items
[ key
] = src
;
2407 * Iterate through the module store, removing any item that does not correspond
2408 * (in name and version) to an item in the module registry.
2410 prune: function () {
2413 for ( key
in this.items
) {
2414 module
= key
.slice( 0, key
.indexOf( '@' ) );
2415 if ( getModuleKey( module
) !== key
) {
2416 this.stats
.expired
++;
2417 delete this.items
[ key
];
2418 } else if ( this.items
[ key
].length
> this.MODULE_SIZE_MAX
) {
2419 // This value predates the enforcement of a size limit on cached modules.
2420 delete this.items
[ key
];
2426 * Clear the entire module store right now.
2428 clear: function () {
2431 localStorage
.removeItem( this.getStoreKey() );
2436 * Request a sync of the in-memory store back to persisted localStorage.
2438 * This function debounces updates. The debouncing logic should account
2439 * for the following factors:
2441 * - Writing to localStorage is an expensive operation that must not happen
2442 * during the critical path of initialising and executing module code.
2443 * Instead, it should happen at a later time after modules have been given
2444 * time and priority to do their thing first.
2446 * - This method is called from mw.loader.store.add(), which will be called
2447 * hundreds of times on a typical page, including within the same call-stack
2448 * and eventloop-tick. This is because responses from load.php happen in
2449 * batches. As such, we want to allow all modules from the same load.php
2450 * response to be written to disk with a single flush, not many.
2452 * - Repeatedly deleting and creating timers is non-trivial.
2454 * - localStorage is shared by all pages from the same origin, if multiple
2455 * pages are loaded with different module sets, the possibility exists that
2456 * modules saved by one page will be clobbered by another. The impact of
2457 * this is minor, it merely causes a less efficient cache use, and the
2458 * problem would be corrected by subsequent page views.
2460 * This method is considered internal to mw.loader.store and must only
2461 * be called if the store is enabled.
2466 requestUpdate
: ( function () {
2467 var hasPendingWrites
= false;
2469 function flushWrites() {
2472 // Remove anything from the in-memory store that came from previous page
2473 // loads that no longer corresponds with current module names and versions.
2474 mw
.loader
.store
.prune();
2475 // Process queued module names, serialise their contents to the in-memory store.
2476 while ( mw
.loader
.store
.queue
.length
) {
2477 mw
.loader
.store
.set( mw
.loader
.store
.queue
.shift() );
2480 key
= mw
.loader
.store
.getStoreKey();
2482 // Replacing the content of the module store might fail if the new
2483 // contents would exceed the browser's localStorage size limit. To
2484 // avoid clogging the browser with stale data, always remove the old
2485 // value before attempting to set the new one.
2486 localStorage
.removeItem( key
);
2487 data
= JSON
.stringify( mw
.loader
.store
);
2488 localStorage
.setItem( key
, data
);
2490 mw
.trackError( 'resourceloader.exception', {
2492 source
: 'store-localstorage-update'
2496 // Let the next call to requestUpdate() create a new timer.
2497 hasPendingWrites
= false;
2500 function onTimeout() {
2501 // Defer the actual write via requestIdleCallback
2502 mw
.requestIdleCallback( flushWrites
);
2505 return function () {
2506 // On the first call to requestUpdate(), create a timer that
2507 // waits at least two seconds, then calls onTimeout.
2508 // The main purpose is to allow the current batch of load.php
2509 // responses to complete before we do anything. This batch can
2510 // trigger many hundreds of calls to requestUpdate().
2511 if ( !hasPendingWrites
) {
2512 hasPendingWrites
= true;
2513 setTimeout( onTimeout
, 2000 );
2521 // Skeleton user object, extended by the 'mediawiki.user' module.
2528 * @property {mw.Map}
2532 * @property {mw.Map}
2537 // OOUI widgets specific to MediaWiki
2542 // Attach to window and globally alias
2543 window
.mw
= window
.mediaWiki
= mw
;