8b2aa29dc7197d61f4f71dfc65334fadd0b8b6c5
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
,
20 * FNV132 hash function
22 * This function implements the 32-bit version of FNV-1.
23 * It is equivalent to hash( 'fnv132', ... ) in PHP, except
24 * its output is base 36 rather than hex.
25 * See <https://en.wikipedia.org/wiki/FNV_hash_function>
28 * @param {string} str String to hash
29 * @return {string} hash as an seven-character base 36 string
31 function fnv132( str
) {
32 /* eslint-disable no-bitwise */
33 var hash
= 0x811C9DC5,
36 for ( i
= 0; i
< str
.length
; i
++ ) {
37 hash
+= ( hash
<< 1 ) + ( hash
<< 4 ) + ( hash
<< 7 ) + ( hash
<< 8 ) + ( hash
<< 24 );
38 hash
^= str
.charCodeAt( i
);
41 hash
= ( hash
>>> 0 ).toString( 36 );
42 while ( hash
.length
< 7 ) {
47 /* eslint-enable no-bitwise */
50 function defineFallbacks() {
51 // <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set>
56 StringSet
= window
.Set
|| function StringSet() {
57 var set = Object
.create( null );
58 this.add = function ( value
) {
61 this.has = function ( value
) {
68 * Alias property to the global object.
75 * @param {Mixed} value
77 function setGlobalMapValue( map
, key
, value
) {
78 map
.values
[ key
] = value
;
83 // Deprecation notice for mw.config globals (T58550, T72470)
84 map
=== mw
.config
&& 'Use mw.config instead.'
89 * Log a message to window.console, if possible.
91 * Useful to force logging of some errors that are otherwise hard to detect (i.e., this logs
92 * also in production mode). Gets console references in each invocation instead of caching the
93 * reference, so that debugging tools loaded later are supported (e.g. Firebug Lite in IE).
96 * @param {string} topic Stream name passed by mw.track
97 * @param {Object} data Data passed by mw.track
98 * @param {Error} [data.exception]
99 * @param {string} data.source Error source
100 * @param {string} [data.module] Name of module which caused the error
102 function logError( topic
, data
) {
105 source
= data
.source
,
106 module
= data
.module
,
107 console
= window
.console
;
109 if ( console
&& console
.log
) {
110 msg
= ( e
? 'Exception' : 'Error' ) + ' in ' + source
;
112 msg
+= ' in module ' + module
;
114 msg
+= ( e
? ':' : '.' );
117 // If we have an exception object, log it to the warning channel to trigger
118 // proper stacktraces in browsers that support it.
119 if ( e
&& console
.warn
) {
126 * Create an object that can be read from or written to via methods that allow
127 * interaction both with single and multiple properties at once.
133 * @param {boolean} [global=false] Whether to synchronise =values to the global
134 * window object (for backwards-compatibility with mw.config; T72470). Values are
135 * copied in one direction only. Changes to globals do not reflect in the map.
137 function Map( global
) {
138 this.values
= Object
.create( null );
139 if ( global
=== true ) {
140 // Override #set to also set the global variable
141 this.set = function ( selection
, value
) {
143 if ( arguments
.length
> 1 ) {
144 if ( typeof selection
!== 'string' ) {
147 setGlobalMapValue( this, selection
, value
);
150 if ( typeof selection
=== 'object' ) {
151 for ( s
in selection
) {
152 setGlobalMapValue( this, s
, selection
[ s
] );
165 * Get the value of one or more keys.
167 * If called with no arguments, all values are returned.
169 * @param {string|Array} [selection] Key or array of keys to retrieve values for.
170 * @param {Mixed} [fallback=null] Value for keys that don't exist.
171 * @return {Mixed|Object|null} If selection was a string, returns the value,
172 * If selection was an array, returns an object of key/values.
173 * If no selection is passed, a new object with all key/values is returned.
175 get: function ( selection
, fallback
) {
177 fallback
= arguments
.length
> 1 ? fallback
: null;
179 if ( Array
.isArray( selection
) ) {
181 for ( i
= 0; i
< selection
.length
; i
++ ) {
182 if ( typeof selection
[ i
] === 'string' ) {
183 results
[ selection
[ i
] ] = selection
[ i
] in this.values
?
184 this.values
[ selection
[ i
] ] :
191 if ( typeof selection
=== 'string' ) {
192 return selection
in this.values
?
193 this.values
[ selection
] :
197 if ( selection
=== undefined ) {
199 for ( i
in this.values
) {
200 results
[ i
] = this.values
[ i
];
205 // Invalid selection key
210 * Set one or more key/value pairs.
212 * @param {string|Object} selection Key to set value for, or object mapping keys to values
213 * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
214 * @return {boolean} True on success, false on failure
216 set: function ( selection
, value
) {
218 // Use `arguments.length` because `undefined` is also a valid value.
219 if ( arguments
.length
> 1 ) {
220 if ( typeof selection
!== 'string' ) {
223 this.values
[ selection
] = value
;
226 if ( typeof selection
=== 'object' ) {
227 for ( s
in selection
) {
228 this.values
[ s
] = selection
[ s
];
236 * Check if one or more keys exist.
238 * @param {Mixed} selection Key or array of keys to check
239 * @return {boolean} True if the key(s) exist
241 exists: function ( selection
) {
243 if ( Array
.isArray( selection
) ) {
244 for ( i
= 0; i
< selection
.length
; i
++ ) {
245 if ( typeof selection
[ i
] !== 'string' || !( selection
[ i
] in this.values
) ) {
251 return typeof selection
=== 'string' && selection
in this.values
;
257 log
= ( function () {
259 * Write a verbose message to the browser's console in debug mode.
261 * This method is mainly intended for verbose logging. It is a no-op in production mode.
262 * In ResourceLoader debug mode, it will use the browser's console if available, with
263 * fallback to creating a console interface in the DOM and logging messages there.
265 * See {@link mw.log} for other logging methods.
268 * @param {...string} msg Messages to output to console.
270 var log = function () {},
271 console
= window
.console
;
273 // Note: Keep list of methods in sync with restoration in mediawiki.log.js
274 // when adding or removing mw.log methods below!
277 * Collection of methods to help log messages to the console.
284 * Write a message to the browser console's warning channel.
286 * This method is a no-op in browsers that don't implement the Console API.
288 * @param {...string} msg Messages to output to console
290 log
.warn
= console
&& console
.warn
?
291 Function
.prototype.bind
.call( console
.warn
, console
) :
295 * Write a message to the browser console's error channel.
297 * Most browsers also print a stacktrace when calling this method if the
298 * argument is an Error object.
300 * This method is a no-op in browsers that don't implement the Console API.
303 * @param {...Mixed} msg Messages to output to console
305 log
.error
= console
&& console
.error
?
306 Function
.prototype.bind
.call( console
.error
, console
) :
310 * Create a property on a host object that, when accessed, will produce
311 * a deprecation warning in the console.
313 * @param {Object} obj Host object of deprecated property
314 * @param {string} key Name of property to create in `obj`
315 * @param {Mixed} val The value this property should return when accessed
316 * @param {string} [msg] Optional text to include in the deprecation message
317 * @param {string} [logName=key] Optional custom name for the feature.
318 * This is used instead of `key` in the message and `mw.deprecate` tracking.
320 log
.deprecate = function ( obj
, key
, val
, msg
, logName
) {
322 function maybeLog() {
324 trace
= new Error().stack
;
326 stacks
= new StringSet();
328 if ( !stacks
.has( trace
) ) {
330 name
= logName
|| key
;
331 mw
.track( 'mw.deprecate', name
);
333 'Use of "' + name
+ '" is deprecated.' + ( msg
? ( ' ' + msg
) : '' )
337 // Support: Safari 5.0
338 // Throws "not supported on DOM Objects" for Node or Element objects (incl. document)
339 // Safari 4.0 doesn't have this method, and it was fixed in Safari 5.1.
341 Object
.defineProperty( obj
, key
, {
348 set: function ( newVal
) {
365 redefineFallbacksForTest: function () {
366 if ( !window
.QUnit
) {
367 throw new Error( 'Reset not allowed outside unit tests' );
373 * Get the current time, measured in milliseconds since January 1, 1970 (UTC).
375 * On browsers that implement the Navigation Timing API, this function will produce
376 * floating-point values with microsecond precision that are guaranteed to be monotonic.
377 * On all other browsers, it will fall back to using `Date`.
379 * @return {number} Current time
382 // Optimisation: Define the 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
&& typeof perf
.now
=== 'function' ?
388 function () { return navStart
+ perf
.now(); } :
395 * List of all analytic events emitted so far.
400 trackQueue
: trackQueue
,
402 track: function ( topic
, data
) {
403 trackQueue
.push( { topic
: topic
, timeStamp
: mw
.now(), data
: data
} );
404 // The base module extends this method to fire events here
408 * Track an early error event via mw.track and send it to the window console.
411 * @param {string} topic Topic name
412 * @param {Object} data Data describing the event, encoded as an object; see mw#logError
414 trackError: function ( topic
, data
) {
415 mw
.track( topic
, data
);
416 logError( topic
, data
);
419 // Expose Map constructor
423 * Map of configuration values.
425 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
428 * If `$wgLegacyJavaScriptGlobals` is true, this Map will add its values to the
429 * global `window` object.
431 * @property {mw.Map} config
433 // Dummy placeholder later assigned in ResourceLoaderStartUpModule
437 * Empty object for third-party libraries, for cases where you don't
438 * want to add a new global, or the global is bad and needs containment
446 * Access container for deprecated functionality that can be moved from
447 * from their legacy location and attached to this object (e.g. a global
448 * function that is deprecated and as stop-gap can be exposed through here).
450 * This was reserved for future use but never ended up being used.
452 * @deprecated since 1.22 Let deprecated identifiers keep their original name
453 * and use mw.log#deprecate to create an access container for tracking.
459 * Store for messages.
466 * Store for templates associated with a module.
470 templates
: new Map(),
476 * Client for ResourceLoader server end point.
478 * This client is in charge of maintaining the module registry and state
479 * machine, initiating network (batch) requests for loading modules, as
480 * well as dependency resolution and execution of source code.
482 * For more information, refer to
483 * <https://www.mediawiki.org/wiki/ResourceLoader/Features>
488 loader
: ( function () {
491 * Fired via mw.track on various resource loading errors.
493 * @event resourceloader_exception
494 * @param {Error|Mixed} e The error that was thrown. Almost always an Error
495 * object, but in theory module code could manually throw something else, and that
496 * might also end up here.
497 * @param {string} [module] Name of the module which caused the error. Omitted if the
498 * error is not module-related or the module cannot be easily identified due to
500 * @param {string} source Source of the error. Possible values:
502 * - style: stylesheet error (only affects old IE where a special style loading method
504 * - load-callback: exception thrown by user callback
505 * - module-execute: exception thrown by module code
506 * - resolve: failed to sort dependencies for a module in mw.loader.load
507 * - store-eval: could not evaluate module code cached in localStorage
508 * - store-localstorage-init: localStorage or JSON parse error in mw.loader.store.init
509 * - store-localstorage-json: JSON conversion error in mw.loader.store
510 * - store-localstorage-update: localStorage conversion error in mw.loader.store.
514 * Fired via mw.track on resource loading error conditions.
516 * @event resourceloader_assert
517 * @param {string} source Source of the error. Possible values:
519 * - bug-T59567: failed to cache script due to an Opera function -> string conversion
520 * bug; see <https://phabricator.wikimedia.org/T59567> for details
524 * Mapping of registered modules.
526 * See #implement and #execute for exact details on support for script, style and messages.
532 * // From mw.loader.register()
533 * 'version': '########' (hash)
534 * 'dependencies': ['required.foo', 'bar.also', ...]
535 * 'group': 'somegroup', (or) null
536 * 'source': 'local', (or) 'anotherwiki'
537 * 'skip': 'return !!window.Example', (or) null
538 * 'module': export Object
540 * // Set from execute() or mw.loader.state()
541 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error', or 'missing'
543 * // Optionally added at run-time by mw.loader.implement()
545 * 'script': closure, array of urls, or string
546 * 'style': { ... } (see #execute)
547 * 'messages': { 'key': 'value', ... }
554 * The module is known to the system but not yet required.
555 * Meta data is registered via mw.loader#register. Calls to that method are
556 * generated server-side by the startup module.
558 * The module was required through mw.loader (either directly or as dependency of
559 * another module). The client will fetch module contents from the server.
560 * The contents are then stashed in the registry via mw.loader#implement.
562 * The module has been loaded from the server and stashed via mw.loader#implement.
563 * Once the module has no more dependencies in-flight, the module will be executed,
564 * controlled via #requestPropagation and #doPropagation.
566 * The module is being executed.
568 * The module has been successfully executed.
570 * The module (or one of its dependencies) produced an error during execution.
572 * The module was registered client-side and requested, but the server denied knowledge
573 * of the module's existence.
578 var registry
= Object
.create( null ),
579 // Mapping of sources, keyed by source-id, values are strings.
584 // 'sourceId': 'http://example.org/w/load.php'
587 sources
= Object
.create( null ),
589 // For queueModuleScript()
590 handlingPendingRequests
= false,
591 pendingRequests
= [],
593 // List of modules to be loaded
597 * List of callback jobs waiting for modules to be ready.
599 * Jobs are created by #enqueue() and run by #doPropagation().
600 * Typically when a job is created for a module, the job's dependencies contain
601 * both the required module and all its recursive dependencies.
606 * 'dependencies': [ module names ],
607 * 'ready': Function callback
608 * 'error': Function callback
611 * @property {Object[]} jobs
616 // For #requestPropagation() and #doPropagation()
617 willPropagate
= false,
622 * @property {Array} baseModules
624 baseModules
= $VARS
.baseModules
,
627 * For #addEmbeddedCSS() and #addLink()
630 * @property {HTMLElement|null} marker
632 marker
= document
.querySelector( 'meta[name="ResourceLoaderDynamicStyles"]' ),
634 // For #addEmbeddedCSS()
636 rAF
= window
.requestAnimationFrame
|| setTimeout
;
639 * Create a new style element and add it to the DOM.
642 * @param {string} text CSS text
643 * @param {Node|null} [nextNode] The element where the style tag
644 * should be inserted before
645 * @return {HTMLElement} Reference to the created style element
647 function newStyleTag( text
, nextNode
) {
648 var el
= document
.createElement( 'style' );
649 el
.appendChild( document
.createTextNode( text
) );
650 if ( nextNode
&& nextNode
.parentNode
) {
651 nextNode
.parentNode
.insertBefore( el
, nextNode
);
653 document
.head
.appendChild( el
);
660 * @param {Object} cssBuffer
662 function flushCssBuffer( cssBuffer
) {
664 // Mark this object as inactive now so that further calls to addEmbeddedCSS() from
665 // the callbacks go to a new buffer instead of this one (T105973)
666 cssBuffer
.active
= false;
667 newStyleTag( cssBuffer
.cssText
, marker
);
668 for ( i
= 0; i
< cssBuffer
.callbacks
.length
; i
++ ) {
669 cssBuffer
.callbacks
[ i
]();
674 * Add a bit of CSS text to the current browser page.
676 * The creation and insertion of the `<style>` element is debounced for two reasons:
678 * - Performing the insertion before the next paint round via requestAnimationFrame
679 * avoids forced or wasted style recomputations, which are expensive in browsers.
680 * - Reduce how often new stylesheets are inserted by letting additional calls to this
681 * function accumulate into a buffer for at least one JavaScript tick. Modules are
682 * received from the server in batches, which means there is likely going to be many
683 * calls to this function in a row within the same tick / the same call stack.
687 * @param {string} cssText CSS text to be added in a `<style>` tag.
688 * @param {Function} callback Called after the insertion has occurred
690 function addEmbeddedCSS( cssText
, callback
) {
691 // Create a buffer if:
692 // - We don't have one yet.
693 // - The previous one is closed.
694 // - The next CSS chunk syntactically needs to be at the start of a stylesheet (T37562).
695 if ( !nextCssBuffer
|| nextCssBuffer
.active
=== false || cssText
.slice( 0, '@import'.length
) === '@import' ) {
703 // Linebreak for somewhat distinguishable sections
704 nextCssBuffer
.cssText
+= '\n' + cssText
;
705 nextCssBuffer
.callbacks
.push( callback
);
707 if ( nextCssBuffer
.active
=== null ) {
708 nextCssBuffer
.active
= true;
709 // The flushCssBuffer callback has its parameter bound by reference, which means
710 // 1) We can still extend the buffer from our object reference after this point.
711 // 2) We can safely re-assign the variable (not the object) to start a new buffer.
712 rAF( flushCssBuffer
.bind( null, nextCssBuffer
) );
718 * @param {Array} modules List of module names
719 * @return {string} Hash of concatenated version hashes.
721 function getCombinedVersion( modules
) {
722 var hashes
= modules
.reduce( function ( result
, module
) {
723 return result
+ registry
[ module
].version
;
725 return fnv132( hashes
);
729 * Determine whether all dependencies are in state 'ready', which means we may
730 * execute the module or job now.
733 * @param {Array} modules Names of modules to be checked
734 * @return {boolean} True if all modules are in state 'ready', false otherwise
736 function allReady( modules
) {
738 for ( i
= 0; i
< modules
.length
; i
++ ) {
739 if ( mw
.loader
.getState( modules
[ i
] ) !== 'ready' ) {
747 * Determine whether all direct and base dependencies are in state 'ready'
750 * @param {string} module Name of the module to be checked
751 * @return {boolean} True if all direct/base dependencies are in state 'ready'; false otherwise
753 function allWithImplicitReady( module
) {
754 return allReady( registry
[ module
].dependencies
) &&
755 ( baseModules
.indexOf( module
) !== -1 || allReady( baseModules
) );
759 * Determine whether all dependencies are in state 'ready', which means we may
760 * execute the module or job now.
763 * @param {Array} modules Names of modules to be checked
764 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
766 function anyFailed( modules
) {
768 for ( i
= 0; i
< modules
.length
; i
++ ) {
769 state
= mw
.loader
.getState( modules
[ i
] );
770 if ( state
=== 'error' || state
=== 'missing' ) {
778 * Handle propagation of module state changes and reactions to them.
780 * - When a module reaches a failure state, this should be propagated to
781 * modules that depend on the failed module.
782 * - When a module reaches a final state, pending job callbacks for the
783 * module from mw.loader.using() should be called.
784 * - When a module reaches the 'ready' state from #execute(), consider
785 * executing dependant modules now having their dependencies satisfied.
786 * - When a module reaches the 'loaded' state from mw.loader.implement,
787 * consider executing it, if it has no unsatisfied dependencies.
791 function doPropagation() {
792 var errorModule
, baseModuleError
, module
, i
, failed
, job
,
795 // Keep going until the last iteration performed no actions.
797 didPropagate
= false;
799 // Stage 1: Propagate failures
800 while ( errorModules
.length
) {
801 errorModule
= errorModules
.shift();
802 baseModuleError
= baseModules
.indexOf( errorModule
) !== -1;
803 for ( module
in registry
) {
804 if ( registry
[ module
].state
!== 'error' && registry
[ module
].state
!== 'missing' ) {
805 if ( baseModuleError
&& baseModules
.indexOf( module
) === -1 ) {
806 // Propate error from base module to all regular (non-base) modules
807 registry
[ module
].state
= 'error';
809 } else if ( registry
[ module
].dependencies
.indexOf( errorModule
) !== -1 ) {
810 // Propagate error from dependency to depending module
811 registry
[ module
].state
= 'error';
812 // .. and propagate it further
813 errorModules
.push( module
);
820 // Stage 2: Execute 'loaded' modules with no unsatisfied dependencies
821 for ( module
in registry
) {
822 if ( registry
[ module
].state
=== 'loaded' && allWithImplicitReady( module
) ) {
823 // Recursively execute all dependent modules that were already loaded
824 // (waiting for execution) and no longer have unsatisfied dependencies.
825 // Base modules may have dependencies amongst eachother to ensure correct
826 // execution order. Regular modules wait for all base modules.
827 // eslint-disable-next-line no-use-before-define
833 // Stage 3: Invoke job callbacks that are no longer blocked
834 for ( i
= 0; i
< jobs
.length
; i
++ ) {
836 failed
= anyFailed( job
.dependencies
);
837 if ( failed
|| allReady( job
.dependencies
) ) {
841 if ( failed
&& job
.error
) {
842 job
.error( new Error( 'Module has failed dependencies' ), job
.dependencies
);
843 } else if ( !failed
&& job
.ready
) {
847 // A user-defined callback raised an exception.
848 // Swallow it to protect our state machine!
849 mw
.trackError( 'resourceloader.exception', {
851 source
: 'load-callback'
857 } while ( didPropagate
);
859 willPropagate
= false;
863 * Request a (debounced) call to doPropagation().
867 function requestPropagation() {
868 if ( willPropagate
) {
869 // Already scheduled, or, we're already in a doPropagation stack.
872 willPropagate
= true;
873 // Yield for two reasons:
874 // * Allow successive calls to mw.loader.implement() from the same
875 // load.php response, or from the same asyncEval() to be in the
876 // propagation batch.
877 // * Allow the browser to breathe between the reception of
878 // module source code and the execution of it.
880 // Use a high priority because the user may be waiting for interactions
881 // to start being possible. But, first provide a moment (up to 'timeout')
882 // for native input event handling (e.g. scrolling/typing/clicking).
883 mw
.requestIdleCallback( doPropagation
, { timeout
: 1 } );
887 * Update a module's state in the registry and make sure any neccesary
888 * propagation will occur. See #doPropagation for more about propagation.
889 * See #registry for more about how states are used.
892 * @param {string} module
893 * @param {string} state
895 function setAndPropagate( module
, state
) {
896 registry
[ module
].state
= state
;
897 if ( state
=== 'loaded' || state
=== 'ready' || state
=== 'error' || state
=== 'missing' ) {
898 if ( state
=== 'ready' ) {
899 // Queue to later be synced to the local module store.
900 mw
.loader
.store
.add( module
);
901 } else if ( state
=== 'error' || state
=== 'missing' ) {
902 errorModules
.push( module
);
904 requestPropagation();
909 * Resolve dependencies and detect circular references.
912 * @param {string} module Name of the top-level module whose dependencies shall be
913 * resolved and sorted.
914 * @param {Array} resolved Returns a topological sort of the given module and its
915 * dependencies, such that later modules depend on earlier modules. The array
916 * contains the module names. If the array contains already some module names,
917 * this function appends its result to the pre-existing array.
918 * @param {StringSet} [unresolved] Used to track the current dependency
919 * chain, and to report loops in the dependency graph.
920 * @throws {Error} If any unregistered module or a dependency loop is encountered
922 function sortDependencies( module
, resolved
, unresolved
) {
925 if ( !( module
in registry
) ) {
926 throw new Error( 'Unknown dependency: ' + module
);
929 if ( registry
[ module
].skip
!== null ) {
930 // eslint-disable-next-line no-new-func
931 skip
= new Function( registry
[ module
].skip
);
932 registry
[ module
].skip
= null;
934 registry
[ module
].skipped
= true;
935 registry
[ module
].dependencies
= [];
936 setAndPropagate( module
, 'ready' );
941 if ( resolved
.indexOf( module
) !== -1 ) {
942 // Module already resolved; nothing to do
945 // Create unresolved if not passed in
947 unresolved
= new StringSet();
951 if ( baseModules
.indexOf( module
) === -1 ) {
952 baseModules
.forEach( function ( baseModule
) {
953 if ( resolved
.indexOf( baseModule
) === -1 ) {
954 resolved
.push( baseModule
);
959 // Tracks down dependencies
960 deps
= registry
[ module
].dependencies
;
961 unresolved
.add( module
);
962 for ( i
= 0; i
< deps
.length
; i
++ ) {
963 if ( resolved
.indexOf( deps
[ i
] ) === -1 ) {
964 if ( unresolved
.has( deps
[ i
] ) ) {
966 'Circular reference detected: ' + module
+ ' -> ' + deps
[ i
]
970 sortDependencies( deps
[ i
], resolved
, unresolved
);
973 resolved
.push( module
);
977 * Get names of module that a module depends on, in their proper dependency order.
980 * @param {string[]} modules Array of string module names
981 * @return {Array} List of dependencies, including 'module'.
982 * @throws {Error} If an unregistered module or a dependency loop is encountered
984 function resolve( modules
) {
985 var i
, resolved
= [];
986 for ( i
= 0; i
< modules
.length
; i
++ ) {
987 sortDependencies( modules
[ i
], resolved
);
993 * Like #resolve(), except it will silently ignore modules that
994 * are missing or have missing dependencies.
997 * @param {string[]} modules Array of string module names
998 * @return {Array} List of dependencies.
1000 function resolveStubbornly( modules
) {
1001 var i
, saved
, resolved
= [];
1002 for ( i
= 0; i
< modules
.length
; i
++ ) {
1003 saved
= resolved
.slice();
1005 sortDependencies( modules
[ i
], resolved
);
1007 // This module is unknown or has unknown dependencies.
1008 // Undo any incomplete resolutions made and keep going.
1010 mw
.trackError( 'resourceloader.exception', {
1020 * Resolve a relative file path.
1022 * For example, resolveRelativePath( '../foo.js', 'resources/src/bar/bar.js' )
1023 * returns 'resources/src/foo.js'.
1025 * @param {string} relativePath Relative file path, starting with ./ or ../
1026 * @param {string} basePath Path of the file (not directory) relativePath is relative to
1027 * @return {string|null} Resolved path, or null if relativePath does not start with ./ or ../
1029 function resolveRelativePath( relativePath
, basePath
) {
1030 var prefixes
, prefix
, baseDirParts
,
1031 relParts
= relativePath
.match( /^((?:\.\.?\/)+)(.*)$/ );
1037 baseDirParts
= basePath
.split( '/' );
1038 // basePath looks like 'foo/bar/baz.js', so baseDirParts looks like [ 'foo', 'bar, 'baz.js' ]
1039 // Remove the file component at the end, so that we are left with only the directory path
1042 prefixes
= relParts
[ 1 ].split( '/' );
1043 // relParts[ 1 ] looks like '../../', so prefixes looks like [ '..', '..', '' ]
1044 // Remove the empty element at the end
1047 // For every ../ in the path prefix, remove one directory level from baseDirParts
1048 while ( ( prefix
= prefixes
.pop() ) !== undefined ) {
1049 if ( prefix
=== '..' ) {
1054 // If there's anything left of the base path, prepend it to the file path
1055 return ( baseDirParts
.length
? baseDirParts
.join( '/' ) + '/' : '' ) + relParts
[ 2 ];
1059 * Make a require() function scoped to a package file
1061 * @param {Object} moduleObj Module object from the registry
1062 * @param {string} basePath Path of the file this is scoped to. Used for relative paths.
1063 * @return {Function}
1065 function makeRequireFunction( moduleObj
, basePath
) {
1066 return function require( moduleName
) {
1067 var fileName
, fileContent
, result
, moduleParam
,
1068 scriptFiles
= moduleObj
.script
.files
;
1069 fileName
= resolveRelativePath( moduleName
, basePath
);
1070 if ( fileName
=== null ) {
1071 // Not a relative path, so it's a module name
1072 return mw
.loader
.require( moduleName
);
1075 if ( !hasOwn
.call( scriptFiles
, fileName
) ) {
1076 throw new Error( 'Cannot require() undefined file ' + fileName
);
1078 if ( hasOwn
.call( moduleObj
.packageExports
, fileName
) ) {
1079 // File has already been executed, return the cached result
1080 return moduleObj
.packageExports
[ fileName
];
1083 fileContent
= scriptFiles
[ fileName
];
1084 if ( typeof fileContent
=== 'function' ) {
1085 moduleParam
= { exports
: {} };
1086 fileContent( makeRequireFunction( moduleObj
, fileName
), moduleParam
);
1087 result
= moduleParam
.exports
;
1089 // fileContent is raw data, just pass it through
1090 result
= fileContent
;
1092 moduleObj
.packageExports
[ fileName
] = result
;
1098 * Load and execute a script.
1101 * @param {string} src URL to script, will be used as the src attribute in the script tag
1102 * @param {Function} [callback] Callback to run after request resolution
1104 function addScript( src
, callback
) {
1105 var script
= document
.createElement( 'script' );
1107 script
.onload
= script
.onerror = function () {
1108 if ( script
.parentNode
) {
1109 script
.parentNode
.removeChild( script
);
1117 document
.head
.appendChild( script
);
1121 * Queue the loading and execution of a script for a particular module.
1123 * This does for debug mode what runScript() does for production.
1126 * @param {string} src URL of the script
1127 * @param {string} moduleName Name of currently executing module
1128 * @param {Function} callback Callback to run after addScript() resolution
1130 function queueModuleScript( src
, moduleName
, callback
) {
1131 pendingRequests
.push( function () {
1132 // Keep in sync with execute()/runScript().
1133 if ( moduleName
!== 'jquery' ) {
1134 window
.require
= mw
.loader
.require
;
1135 window
.module
= registry
[ moduleName
].module
;
1137 addScript( src
, function () {
1138 // 'module.exports' should not persist after the file is executed to
1139 // avoid leakage to unrelated code. 'require' should be kept, however,
1140 // as asynchronous access to 'require' is allowed and expected. (T144879)
1141 delete window
.module
;
1143 // Start the next one (if any)
1144 if ( pendingRequests
[ 0 ] ) {
1145 pendingRequests
.shift()();
1147 handlingPendingRequests
= false;
1151 if ( !handlingPendingRequests
&& pendingRequests
[ 0 ] ) {
1152 handlingPendingRequests
= true;
1153 pendingRequests
.shift()();
1158 * Utility function for execute()
1161 * @param {string} [media] Media attribute
1162 * @param {string} url URL
1164 function addLink( media
, url
) {
1165 var el
= document
.createElement( 'link' );
1167 el
.rel
= 'stylesheet';
1168 if ( media
&& media
!== 'all' ) {
1171 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1172 // see #addEmbeddedCSS, T33676, T43331, and T49277 for details.
1175 if ( marker
&& marker
.parentNode
) {
1176 marker
.parentNode
.insertBefore( el
, marker
);
1178 document
.head
.appendChild( el
);
1184 * @param {string} code JavaScript code
1186 function domEval( code
) {
1187 var script
= document
.createElement( 'script' );
1188 if ( mw
.config
.get( 'wgCSPNonce' ) !== false ) {
1189 script
.nonce
= mw
.config
.get( 'wgCSPNonce' );
1192 document
.head
.appendChild( script
);
1193 script
.parentNode
.removeChild( script
);
1197 * Add one or more modules to the module load queue.
1202 * @param {string[]} dependencies Array of module names in the registry
1203 * @param {Function} [ready] Callback to execute when all dependencies are ready
1204 * @param {Function} [error] Callback to execute when any dependency fails
1206 function enqueue( dependencies
, ready
, error
) {
1207 if ( allReady( dependencies
) ) {
1208 // Run ready immediately
1209 if ( ready
!== undefined ) {
1215 if ( anyFailed( dependencies
) ) {
1216 if ( error
!== undefined ) {
1217 // Execute error immediately if any dependencies have errors
1219 new Error( 'One or more dependencies failed to load' ),
1226 // Not all dependencies are ready, add to the load queue...
1228 // Add ready and error callbacks if they were given
1229 if ( ready
!== undefined || error
!== undefined ) {
1231 // Narrow down the list to modules that are worth waiting for
1232 dependencies
: dependencies
.filter( function ( module
) {
1233 var state
= registry
[ module
].state
;
1234 return state
=== 'registered' || state
=== 'loaded' || state
=== 'loading' || state
=== 'executing';
1241 dependencies
.forEach( function ( module
) {
1242 // Only queue modules that are still in the initial 'registered' state
1243 // (not ones already loading, ready or error).
1244 if ( registry
[ module
].state
=== 'registered' && queue
.indexOf( module
) === -1 ) {
1245 // Private modules must be embedded in the page. Don't bother queuing
1246 // these as the server will deny them anyway (T101806).
1247 if ( registry
[ module
].group
=== 'private' ) {
1248 setAndPropagate( module
, 'error' );
1251 queue
.push( module
);
1259 * Executes a loaded module, making it ready to use
1262 * @param {string} module Module name to execute
1264 function execute( module
) {
1265 var key
, value
, media
, i
, urls
, cssHandle
, siteDeps
, siteDepErr
, runScript
,
1268 if ( registry
[ module
].state
!== 'loaded' ) {
1269 throw new Error( 'Module in state "' + registry
[ module
].state
+ '" may not be executed: ' + module
);
1272 registry
[ module
].state
= 'executing';
1273 $CODE
.profileExecuteStart();
1275 runScript = function () {
1276 var script
, markModuleReady
, nestedAddScript
, mainScript
;
1278 $CODE
.profileScriptStart();
1279 script
= registry
[ module
].script
;
1280 markModuleReady = function () {
1281 $CODE
.profileScriptEnd();
1282 setAndPropagate( module
, 'ready' );
1284 nestedAddScript = function ( arr
, callback
, i
) {
1285 // Recursively call queueModuleScript() in its own callback
1286 // for each element of arr.
1287 if ( i
>= arr
.length
) {
1288 // We're at the end of the array
1293 queueModuleScript( arr
[ i
], module
, function () {
1294 nestedAddScript( arr
, callback
, i
+ 1 );
1299 if ( Array
.isArray( script
) ) {
1300 nestedAddScript( script
, markModuleReady
, 0 );
1302 typeof script
=== 'function' || (
1303 typeof script
=== 'object' &&
1307 if ( typeof script
=== 'function' ) {
1308 // Keep in sync with queueModuleScript() for debug mode
1309 if ( module
=== 'jquery' ) {
1310 // This is a special case for when 'jquery' itself is being loaded.
1311 // - The standard jquery.js distribution does not set `window.jQuery`
1312 // in CommonJS-compatible environments (Node.js, AMD, RequireJS, etc.).
1313 // - MediaWiki's 'jquery' module also bundles jquery.migrate.js, which
1314 // in a CommonJS-compatible environment, will use require('jquery'),
1315 // but that can't work when we're still inside that module.
1318 // Pass jQuery twice so that the signature of the closure which wraps
1319 // the script can bind both '$' and 'jQuery'.
1320 script( window
.$, window
.$, mw
.loader
.require
, registry
[ module
].module
);
1323 mainScript
= script
.files
[ script
.main
];
1324 if ( typeof mainScript
!== 'function' ) {
1325 throw new Error( 'Main script file ' + script
.main
+ ' in module ' + module
+
1326 'must be of type function, is of type ' + typeof mainScript
);
1328 // jQuery parameters are not passed for multi-file modules
1330 makeRequireFunction( registry
[ module
], script
.main
),
1331 registry
[ module
].module
1335 } else if ( typeof script
=== 'string' ) {
1336 // Site and user modules are legacy scripts that run in the global scope.
1337 // This is transported as a string instead of a function to avoid needing
1338 // to use string manipulation to undo the function wrapper.
1343 // Module without script
1347 // Use mw.track instead of mw.log because these errors are common in production mode
1348 // (e.g. undefined variable), and mw.log is only enabled in debug mode.
1349 setAndPropagate( module
, 'error' );
1350 $CODE
.profileScriptEnd();
1351 mw
.trackError( 'resourceloader.exception', {
1354 source
: 'module-execute'
1359 // Add localizations to message system
1360 if ( registry
[ module
].messages
) {
1361 mw
.messages
.set( registry
[ module
].messages
);
1364 // Initialise templates
1365 if ( registry
[ module
].templates
) {
1366 mw
.templates
.set( module
, registry
[ module
].templates
);
1369 // Adding of stylesheets is asynchronous via addEmbeddedCSS().
1370 // The below function uses a counting semaphore to make sure we don't call
1371 // runScript() until after this module's stylesheets have been inserted
1373 cssHandle = function () {
1374 // Increase semaphore, when creating a callback for addEmbeddedCSS.
1376 return function () {
1378 // Decrease semaphore, when said callback is invoked.
1380 if ( cssPending
=== 0 ) {
1382 // This callback is exposed to addEmbeddedCSS, which is outside the execute()
1383 // function and is not concerned with state-machine integrity. In turn,
1384 // addEmbeddedCSS() actually exposes stuff further into the browser (rAF).
1385 // If increment and decrement callbacks happen in the wrong order, or start
1386 // again afterwards, then this branch could be reached multiple times.
1387 // To protect the integrity of the state-machine, prevent that from happening
1388 // by making runScript() cannot be called more than once. We store a private
1389 // reference when we first reach this branch, then deference the original, and
1390 // call our reference to it.
1391 runScriptCopy
= runScript
;
1392 runScript
= undefined;
1398 // Process styles (see also mw.loader.implement)
1399 // * back-compat: { <media>: css }
1400 // * back-compat: { <media>: [url, ..] }
1401 // * { "css": [css, ..] }
1402 // * { "url": { <media>: [url, ..] } }
1403 if ( registry
[ module
].style
) {
1404 for ( key
in registry
[ module
].style
) {
1405 value
= registry
[ module
].style
[ key
];
1408 if ( key
!== 'url' && key
!== 'css' ) {
1409 // Backwards compatibility, key is a media-type
1410 if ( typeof value
=== 'string' ) {
1411 // back-compat: { <media>: css }
1412 // Ignore 'media' because it isn't supported (nor was it used).
1413 // Strings are pre-wrapped in "@media". The media-type was just ""
1414 // (because it had to be set to something).
1415 // This is one of the reasons why this format is no longer used.
1416 addEmbeddedCSS( value
, cssHandle() );
1418 // back-compat: { <media>: [url, ..] }
1424 // Array of css strings in key 'css',
1425 // or back-compat array of urls from media-type
1426 if ( Array
.isArray( value
) ) {
1427 for ( i
= 0; i
< value
.length
; i
++ ) {
1428 if ( key
=== 'bc-url' ) {
1429 // back-compat: { <media>: [url, ..] }
1430 addLink( media
, value
[ i
] );
1431 } else if ( key
=== 'css' ) {
1432 // { "css": [css, ..] }
1433 addEmbeddedCSS( value
[ i
], cssHandle() );
1436 // Not an array, but a regular object
1437 // Array of urls inside media-type key
1438 } else if ( typeof value
=== 'object' ) {
1439 // { "url": { <media>: [url, ..] } }
1440 for ( media
in value
) {
1441 urls
= value
[ media
];
1442 for ( i
= 0; i
< urls
.length
; i
++ ) {
1443 addLink( media
, urls
[ i
] );
1450 // End profiling of execute()-self before we call runScript(),
1451 // which we want to measure separately without overlap.
1452 $CODE
.profileExecuteEnd();
1454 if ( module
=== 'user' ) {
1455 // Implicit dependency on the site module. Not a real dependency because it should
1456 // run after 'site' regardless of whether it succeeds or fails.
1457 // Note: This is a simplified version of mw.loader.using(), inlined here because
1458 // mw.loader.using() is part of mediawiki.base (depends on jQuery; T192623).
1460 siteDeps
= resolve( [ 'site' ] );
1465 if ( siteDepErr
=== undefined ) {
1466 enqueue( siteDeps
, runScript
, runScript
);
1468 } else if ( cssPending
=== 0 ) {
1469 // Regular module without styles
1472 // else: runScript will get called via cssHandle()
1475 function sortQuery( o
) {
1484 for ( key
= 0; key
< a
.length
; key
++ ) {
1485 sorted
[ a
[ key
] ] = o
[ a
[ key
] ];
1491 * Converts a module map of the form `{ foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }`
1492 * to a query string of the form `foo.bar,baz|bar.baz,quux`.
1494 * See `ResourceLoader::makePackedModulesString()` in PHP, of which this is a port.
1495 * On the server, unpacking is done by `ResourceLoaderContext::expandModuleNames()`.
1497 * Note: This is only half of the logic, the other half has to be in #batchRequest(),
1498 * because its implementation needs to keep track of potential string size in order
1499 * to decide when to split the requests due to url size.
1502 * @param {Object} moduleMap Module map
1504 * @return {string} return.str Module query string
1505 * @return {Array} return.list List of module names in matching order
1507 function buildModulesString( moduleMap
) {
1512 function restore( suffix
) {
1516 for ( prefix
in moduleMap
) {
1517 p
= prefix
=== '' ? '' : prefix
+ '.';
1518 str
.push( p
+ moduleMap
[ prefix
].join( ',' ) );
1519 list
.push
.apply( list
, moduleMap
[ prefix
].map( restore
) );
1522 str
: str
.join( '|' ),
1528 * Resolve indexed dependencies.
1530 * ResourceLoader uses an optimisation to save space which replaces module names in
1531 * dependency lists with the index of that module within the array of module
1532 * registration data if it exists. The benefit is a significant reduction in the data
1533 * size of the startup module. This function changes those dependency lists back to
1534 * arrays of strings.
1537 * @param {Array} modules Modules array
1539 function resolveIndexedDependencies( modules
) {
1541 function resolveIndex( dep
) {
1542 return typeof dep
=== 'number' ? modules
[ dep
][ 0 ] : dep
;
1544 for ( i
= 0; i
< modules
.length
; i
++ ) {
1545 deps
= modules
[ i
][ 2 ];
1547 for ( j
= 0; j
< deps
.length
; j
++ ) {
1548 deps
[ j
] = resolveIndex( deps
[ j
] );
1556 * @param {Object} params Map of parameter names to values
1559 function makeQueryString( params
) {
1560 return Object
.keys( params
).map( function ( key
) {
1561 return encodeURIComponent( key
) + '=' + encodeURIComponent( params
[ key
] );
1566 * Create network requests for a batch of modules.
1568 * This is an internal method for #work(). This must not be called directly
1569 * unless the modules are already registered, and no request is in progress,
1570 * and the module state has already been set to `loading`.
1573 * @param {string[]} batch
1575 function batchRequest( batch
) {
1576 var reqBase
, splits
, maxQueryLength
, b
, bSource
, bGroup
,
1577 source
, group
, i
, modules
, sourceLoadScript
,
1578 currReqBase
, currReqBaseLength
, moduleMap
, currReqModules
, l
,
1579 lastDotIndex
, prefix
, suffix
, bytesAdded
;
1582 * Start the currently drafted request to the server.
1586 function doRequest() {
1587 // Optimisation: Inherit (Object.create), not copy ($.extend)
1588 var query
= Object
.create( currReqBase
),
1589 packed
= buildModulesString( moduleMap
);
1590 query
.modules
= packed
.str
;
1591 // The packing logic can change the effective order, even if the input was
1592 // sorted. As such, the call to getCombinedVersion() must use this
1593 // effective order, instead of currReqModules, as otherwise the combined
1594 // version will not match the hash expected by the server based on
1595 // combining versions from the module query string in-order. (T188076)
1596 query
.version
= getCombinedVersion( packed
.list
);
1597 query
= sortQuery( query
);
1598 addScript( sourceLoadScript
+ '?' + makeQueryString( query
) );
1601 if ( !batch
.length
) {
1605 // Always order modules alphabetically to help reduce cache
1606 // misses for otherwise identical content.
1609 // Query parameters common to all requests
1611 skin
: mw
.config
.get( 'skin' ),
1612 lang
: mw
.config
.get( 'wgUserLanguage' ),
1613 debug
: mw
.config
.get( 'debug' )
1615 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', 2000 );
1617 // Split module list by source and by group.
1618 splits
= Object
.create( null );
1619 for ( b
= 0; b
< batch
.length
; b
++ ) {
1620 bSource
= registry
[ batch
[ b
] ].source
;
1621 bGroup
= registry
[ batch
[ b
] ].group
;
1622 if ( !splits
[ bSource
] ) {
1623 splits
[ bSource
] = Object
.create( null );
1625 if ( !splits
[ bSource
][ bGroup
] ) {
1626 splits
[ bSource
][ bGroup
] = [];
1628 splits
[ bSource
][ bGroup
].push( batch
[ b
] );
1631 for ( source
in splits
) {
1632 sourceLoadScript
= sources
[ source
];
1634 for ( group
in splits
[ source
] ) {
1636 // Cache access to currently selected list of
1637 // modules for this group from this source.
1638 modules
= splits
[ source
][ group
];
1640 // Query parameters common to requests for this module group
1641 // Optimisation: Inherit (Object.create), not copy ($.extend)
1642 currReqBase
= Object
.create( reqBase
);
1643 // User modules require a user name in the query string.
1644 if ( group
=== 'user' && mw
.config
.get( 'wgUserName' ) !== null ) {
1645 currReqBase
.user
= mw
.config
.get( 'wgUserName' );
1648 // In addition to currReqBase, doRequest() will also add 'modules' and 'version'.
1649 // > '&modules='.length === 9
1650 // > '&version=1234567'.length === 16
1652 currReqBaseLength
= makeQueryString( currReqBase
).length
+ 25;
1654 // We may need to split up the request to honor the query string length limit,
1655 // so build it piece by piece.
1656 l
= currReqBaseLength
;
1657 moduleMap
= Object
.create( null ); // { prefix: [ suffixes ] }
1658 currReqModules
= [];
1660 for ( i
= 0; i
< modules
.length
; i
++ ) {
1661 // Determine how many bytes this module would add to the query string
1662 lastDotIndex
= modules
[ i
].lastIndexOf( '.' );
1663 // If lastDotIndex is -1, substr() returns an empty string
1664 prefix
= modules
[ i
].substr( 0, lastDotIndex
);
1665 suffix
= modules
[ i
].slice( lastDotIndex
+ 1 );
1666 bytesAdded
= moduleMap
[ prefix
] ?
1667 suffix
.length
+ 3 : // '%2C'.length == 3
1668 modules
[ i
].length
+ 3; // '%7C'.length == 3
1670 // If the url would become too long, create a new one, but don't create empty requests
1671 if ( maxQueryLength
> 0 && currReqModules
.length
&& l
+ bytesAdded
> maxQueryLength
) {
1672 // Dispatch what we've got...
1674 // .. and start again.
1675 l
= currReqBaseLength
;
1676 moduleMap
= Object
.create( null );
1677 currReqModules
= [];
1679 mw
.track( 'resourceloader.splitRequest', { maxQueryLength
: maxQueryLength
} );
1681 if ( !moduleMap
[ prefix
] ) {
1682 moduleMap
[ prefix
] = [];
1685 moduleMap
[ prefix
].push( suffix
);
1686 currReqModules
.push( modules
[ i
] );
1688 // If there's anything left in moduleMap, request that too
1689 if ( currReqModules
.length
) {
1698 * @param {string[]} implementations Array containing pieces of JavaScript code in the
1699 * form of calls to mw.loader#implement().
1700 * @param {Function} cb Callback in case of failure
1701 * @param {Error} cb.err
1703 function asyncEval( implementations
, cb
) {
1704 if ( !implementations
.length
) {
1707 mw
.requestIdleCallback( function () {
1709 domEval( implementations
.join( ';' ) );
1717 * Make a versioned key for a specific module.
1720 * @param {string} module Module name
1721 * @return {string|null} Module key in format '`[name]@[version]`',
1722 * or null if the module does not exist
1724 function getModuleKey( module
) {
1725 return module
in registry
? ( module
+ '@' + registry
[ module
].version
) : null;
1730 * @param {string} key Module name or '`[name]@[version]`'
1733 function splitModuleKey( key
) {
1734 var index
= key
.indexOf( '@' );
1735 if ( index
=== -1 ) {
1742 name
: key
.slice( 0, index
),
1743 version
: key
.slice( index
+ 1 )
1749 * @param {string} module
1750 * @param {string|number} [version]
1751 * @param {string[]} [dependencies]
1752 * @param {string} [group]
1753 * @param {string} [source]
1754 * @param {string} [skip]
1756 function registerOne( module
, version
, dependencies
, group
, source
, skip
) {
1757 if ( module
in registry
) {
1758 throw new Error( 'module already registered: ' + module
);
1760 registry
[ module
] = {
1761 // Exposed to execute() for mw.loader.implement() closures.
1762 // Import happens via require().
1766 // module.export objects for each package file inside this module
1768 version
: String( version
|| '' ),
1769 dependencies
: dependencies
|| [],
1770 group
: typeof group
=== 'string' ? group
: null,
1771 source
: typeof source
=== 'string' ? source
: 'local',
1772 state
: 'registered',
1773 skip
: typeof skip
=== 'string' ? skip
: null
1777 /* Public Members */
1780 * The module registry is exposed as an aid for debugging and inspecting page
1781 * state; it is not a public interface for modifying the registry.
1787 moduleRegistry
: registry
,
1790 * @inheritdoc #newStyleTag
1793 addStyleTag
: newStyleTag
,
1800 * Start loading of all queued module dependencies.
1805 var q
, batch
, implementations
, sourceModules
;
1809 // Appends a list of modules from the queue to the batch
1810 for ( q
= 0; q
< queue
.length
; q
++ ) {
1811 // Only load modules which are registered
1812 if ( queue
[ q
] in registry
&& registry
[ queue
[ q
] ].state
=== 'registered' ) {
1813 // Prevent duplicate entries
1814 if ( batch
.indexOf( queue
[ q
] ) === -1 ) {
1815 batch
.push( queue
[ q
] );
1816 // Mark registered modules as loading
1817 registry
[ queue
[ q
] ].state
= 'loading';
1822 // Now that the queue has been processed into a batch, clear the queue.
1823 // This MUST happen before we initiate any eval or network request. Otherwise,
1824 // it is possible for a cached script to instantly trigger the same work queue
1825 // again; all before we've cleared it causing each request to include modules
1826 // which are already loaded.
1829 if ( !batch
.length
) {
1833 mw
.loader
.store
.init();
1834 if ( mw
.loader
.store
.enabled
) {
1835 implementations
= [];
1837 batch
= batch
.filter( function ( module
) {
1838 var implementation
= mw
.loader
.store
.get( module
);
1839 if ( implementation
) {
1840 implementations
.push( implementation
);
1841 sourceModules
.push( module
);
1846 asyncEval( implementations
, function ( err
) {
1848 // Not good, the cached mw.loader.implement calls failed! This should
1849 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1850 // Depending on how corrupt the string is, it is likely that some
1851 // modules' implement() succeeded while the ones after the error will
1852 // never run and leave their modules in the 'loading' state forever.
1853 mw
.loader
.store
.stats
.failed
++;
1855 // Since this is an error not caused by an individual module but by
1856 // something that infected the implement call itself, don't take any
1857 // risks and clear everything in this cache.
1858 mw
.loader
.store
.clear();
1860 mw
.trackError( 'resourceloader.exception', {
1862 source
: 'store-eval'
1864 // Re-add the failed ones that are still pending back to the batch
1865 failed
= sourceModules
.filter( function ( module
) {
1866 return registry
[ module
].state
=== 'loading';
1868 batchRequest( failed
);
1872 batchRequest( batch
);
1876 * Register a source.
1878 * The #work() method will use this information to split up requests by source.
1880 * mw.loader.addSource( { mediawikiwiki: 'https://www.mediawiki.org/w/load.php' } );
1883 * @param {Object} ids An object mapping ids to load.php end point urls
1884 * @throws {Error} If source id is already registered
1886 addSource: function ( ids
) {
1889 if ( id
in sources
) {
1890 throw new Error( 'source already registered: ' + id
);
1892 sources
[ id
] = ids
[ id
];
1897 * Register a module, letting the system know about it and its properties.
1899 * The startup module calls this method.
1901 * When using multiple module registration by passing an array, dependencies that
1902 * are specified as references to modules within the array will be resolved before
1903 * the modules are registered.
1905 * @param {string|Array} modules Module name or array of arrays, each containing
1906 * a list of arguments compatible with this method
1907 * @param {string|number} [version] Module version hash (falls backs to empty string)
1908 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1909 * @param {string[]} [dependencies] Array of module names on which this module depends.
1910 * @param {string} [group=null] Group which the module is in
1911 * @param {string} [source='local'] Name of the source
1912 * @param {string} [skip=null] Script body of the skip function
1914 register: function ( modules
) {
1916 if ( typeof modules
=== 'object' ) {
1917 resolveIndexedDependencies( modules
);
1918 // Optimisation: Up to 55% faster.
1919 // Typically called only once, and with a batch.
1920 // See <https://gist.github.com/Krinkle/f06fdb3de62824c6c16f02a0e6ce0e66>
1921 // Benchmarks taught us that the code for adding an object to `registry`
1922 // should actually be inline, or in a simple function that does no
1923 // arguments manipulation, and isn't also the caller itself.
1924 // JS semantics make it hard to optimise recursion to a different
1925 // signature of itself.
1926 for ( i
= 0; i
< modules
.length
; i
++ ) {
1927 registerOne
.apply( null, modules
[ i
] );
1930 registerOne
.apply( null, arguments
);
1935 * Implement a module given the components that make up the module.
1937 * When #load() or #using() requests one or more modules, the server
1938 * response contain calls to this function.
1940 * @param {string} module Name of module and current module version. Formatted
1941 * as '`[name]@[version]`". This version should match the requested version
1942 * (from #batchRequest and #registry). This avoids race conditions (T117587).
1943 * For back-compat with MediaWiki 1.27 and earlier, the version may be omitted.
1944 * @param {Function|Array|string|Object} [script] Module code. This can be a function,
1945 * a list of URLs to load via `<script src>`, a string for `$.globalEval()`, or an
1946 * object like {"files": {"foo.js":function, "bar.js": function, ...}, "main": "foo.js"}.
1947 * If an object is provided, the main file will be executed immediately, and the other
1948 * files will only be executed if loaded via require(). If a function or string is
1949 * provided, it will be executed/evaluated immediately. If an array is provided, all
1950 * URLs in the array will be loaded immediately, and executed as soon as they arrive.
1951 * @param {Object} [style] Should follow one of the following patterns:
1953 * { "css": [css, ..] }
1954 * { "url": { <media>: [url, ..] } }
1956 * And for backwards compatibility (needs to be supported forever due to caching):
1959 * { <media>: [url, ..] }
1961 * The reason css strings are not concatenated anymore is T33676. We now check
1962 * whether it's safe to extend the stylesheet.
1965 * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1966 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1968 implement: function ( module
, script
, style
, messages
, templates
) {
1969 var split
= splitModuleKey( module
),
1971 version
= split
.version
;
1972 // Automatically register module
1973 if ( !( name
in registry
) ) {
1974 mw
.loader
.register( name
);
1976 // Check for duplicate implementation
1977 if ( registry
[ name
].script
!== undefined ) {
1978 throw new Error( 'module already implemented: ' + name
);
1981 // Without this reset, if there is a version mismatch between the
1982 // requested and received module version, then mw.loader.store would
1983 // cache the response under the requested key. Thus poisoning the cache
1984 // indefinitely with a stale value. (T117587)
1985 registry
[ name
].version
= version
;
1987 // Attach components
1988 registry
[ name
].script
= script
|| null;
1989 registry
[ name
].style
= style
|| null;
1990 registry
[ name
].messages
= messages
|| null;
1991 registry
[ name
].templates
= templates
|| null;
1992 // The module may already have been marked as erroneous
1993 if ( registry
[ name
].state
!== 'error' && registry
[ name
].state
!== 'missing' ) {
1994 setAndPropagate( name
, 'loaded' );
1999 * Load an external script or one or more modules.
2001 * This method takes a list of unrelated modules. Use cases:
2003 * - A web page will be composed of many different widgets. These widgets independently
2004 * queue their ResourceLoader modules (`OutputPage::addModules()`). If any of them
2005 * have problems, or are no longer known (e.g. cached HTML), the other modules
2006 * should still be loaded.
2007 * - This method is used for preloading, which must not throw. Later code that
2008 * calls #using() will handle the error.
2010 * @param {string|Array} modules Either the name of a module, array of modules,
2011 * or a URL of an external script or style
2012 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
2013 * external script or style; acceptable values are "text/css" and
2014 * "text/javascript"; if no type is provided, text/javascript is assumed.
2016 load: function ( modules
, type
) {
2019 // Allow calling with a url or single dependency as a string
2020 if ( typeof modules
=== 'string' ) {
2021 // "https://example.org/x.js", "http://example.org/x.js", "//example.org/x.js", "/x.js"
2022 if ( /^(https?:)?\/?\//.test( modules
) ) {
2023 if ( type
=== 'text/css' ) {
2024 l
= document
.createElement( 'link' );
2025 l
.rel
= 'stylesheet';
2027 document
.head
.appendChild( l
);
2030 if ( type
=== 'text/javascript' || type
=== undefined ) {
2031 addScript( modules
);
2035 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type
);
2037 // Called with single module
2038 modules
= [ modules
];
2041 // Filter out top-level modules that are unknown or failed to load before.
2042 filtered
= modules
.filter( function ( module
) {
2043 var state
= mw
.loader
.getState( module
);
2044 return state
!== 'error' && state
!== 'missing';
2046 // Resolve remaining list using the known dependency tree.
2047 // This also filters out modules with unknown dependencies. (T36853)
2048 filtered
= resolveStubbornly( filtered
);
2049 // Some modules are not yet ready, add to module load queue.
2050 enqueue( filtered
, undefined, undefined );
2054 * Change the state of one or more modules.
2056 * @param {Object} states Object of module name/state pairs
2058 state: function ( states
) {
2060 for ( module
in states
) {
2061 state
= states
[ module
];
2062 if ( !( module
in registry
) ) {
2063 mw
.loader
.register( module
);
2065 setAndPropagate( module
, state
);
2070 * Get the version of a module.
2072 * @param {string} module Name of module
2073 * @return {string|null} The version, or null if the module (or its version) is not
2076 getVersion: function ( module
) {
2077 return module
in registry
? registry
[ module
].version
: null;
2081 * Get the state of a module.
2083 * @param {string} module Name of module
2084 * @return {string|null} The state, or null if the module (or its state) is not
2087 getState: function ( module
) {
2088 return module
in registry
? registry
[ module
].state
: null;
2092 * Get the names of all registered modules.
2096 getModuleNames: function () {
2097 return Object
.keys( registry
);
2101 * Get the exported value of a module.
2103 * This static method is publicly exposed for debugging purposes
2104 * only and must not be used in production code. In production code,
2105 * please use the dynamically provided `require()` function instead.
2107 * In case of lazy-loaded modules via mw.loader#using(), the returned
2108 * Promise provides the function, see #using() for examples.
2112 * @param {string} moduleName Module name
2113 * @return {Mixed} Exported value
2115 require: function ( moduleName
) {
2116 var state
= mw
.loader
.getState( moduleName
);
2118 // Only ready modules can be required
2119 if ( state
!== 'ready' ) {
2120 // Module may've forgotten to declare a dependency
2121 throw new Error( 'Module "' + moduleName
+ '" is not loaded.' );
2124 return registry
[ moduleName
].module
.exports
;
2128 * On browsers that implement the localStorage API, the module store serves as a
2129 * smart complement to the browser cache. Unlike the browser cache, the module store
2130 * can slice a concatenated response from ResourceLoader into its constituent
2131 * modules and cache each of them separately, using each module's versioning scheme
2132 * to determine when the cache should be invalidated.
2136 * @class mw.loader.store
2139 // Whether the store is in use on this page.
2142 // Modules whose string representation exceeds 100 kB are
2143 // ineligible for storage. See bug T66721.
2144 MODULE_SIZE_MAX
: 100 * 1000,
2146 // The contents of the store, mapping '[name]@[version]' keys
2147 // to module implementations.
2150 // Names of modules to be stored during the next update.
2151 // See add() and update().
2155 stats
: { hits
: 0, misses
: 0, expired
: 0, failed
: 0 },
2158 * Construct a JSON-serializable object representing the content of the store.
2160 * @return {Object} Module store contents.
2162 toJSON: function () {
2163 return { items
: mw
.loader
.store
.items
, vary
: mw
.loader
.store
.getVary() };
2167 * Get the localStorage key for the entire module store. The key references
2168 * $wgDBname to prevent clashes between wikis which share a common host.
2170 * @return {string} localStorage item key
2172 getStoreKey: function () {
2173 return 'MediaWikiModuleStore:' + mw
.config
.get( 'wgDBname' );
2177 * Get a key on which to vary the module cache.
2179 * @return {string} String of concatenated vary conditions.
2181 getVary: function () {
2182 return mw
.config
.get( 'skin' ) + ':' +
2183 mw
.config
.get( 'wgResourceLoaderStorageVersion' ) + ':' +
2184 mw
.config
.get( 'wgUserLanguage' );
2188 * Initialize the store.
2190 * Retrieves store from localStorage and (if successfully retrieved) decoding
2191 * the stored JSON value to a plain object.
2193 * The try / catch block is used for JSON & localStorage feature detection.
2194 * See the in-line documentation for Modernizr's localStorage feature detection
2195 * code for a full account of why we need a try / catch:
2196 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2201 if ( this.enabled
!== null ) {
2207 // Disabled because localStorage quotas are tight and (in Firefox's case)
2208 // shared by multiple origins.
2209 // See T66721, and <https://bugzilla.mozilla.org/show_bug.cgi?id=1064466>.
2210 /Firefox/.test( navigator
.userAgent
) ||
2212 // Disabled by configuration.
2213 !mw
.config
.get( 'wgResourceLoaderStorageEnabled' )
2215 // Clear any previous store to free up space. (T66721)
2217 this.enabled
= false;
2220 if ( mw
.config
.get( 'debug' ) ) {
2221 // Disable module store in debug mode
2222 this.enabled
= false;
2227 // This a string we stored, or `null` if the key does not (yet) exist.
2228 raw
= localStorage
.getItem( this.getStoreKey() );
2229 // If we get here, localStorage is available; mark enabled
2230 this.enabled
= true;
2231 // If null, JSON.parse() will cast to string and re-parse, still null.
2232 data
= JSON
.parse( raw
);
2233 if ( data
&& typeof data
.items
=== 'object' && data
.vary
=== this.getVary() ) {
2234 this.items
= data
.items
;
2238 mw
.trackError( 'resourceloader.exception', {
2240 source
: 'store-localstorage-init'
2244 // If we get here, one of four things happened:
2246 // 1. localStorage did not contain our store key.
2247 // This means `raw` is `null`, and we're on a fresh page view (cold cache).
2248 // The store was enabled, and `items` starts fresh.
2250 // 2. localStorage contained parseable data under our store key,
2251 // but it's not applicable to our current context (see getVary).
2252 // The store was enabled, and `items` starts fresh.
2254 // 3. JSON.parse threw (localStorage contained corrupt data).
2255 // This means `raw` contains a string.
2256 // The store was enabled, and `items` starts fresh.
2258 // 4. localStorage threw (disabled or otherwise unavailable).
2259 // This means `raw` was never assigned.
2260 // We will disable the store below.
2261 if ( raw
=== undefined ) {
2262 // localStorage failed; disable store
2263 this.enabled
= false;
2268 * Retrieve a module from the store and update cache hit stats.
2270 * @param {string} module Module name
2271 * @return {string|boolean} Module implementation or false if unavailable
2273 get: function ( module
) {
2276 if ( !this.enabled
) {
2280 key
= getModuleKey( module
);
2281 if ( key
in this.items
) {
2283 return this.items
[ key
];
2285 this.stats
.misses
++;
2290 * Queue the name of a module that the next update should consider storing.
2293 * @param {string} module Module name
2295 add: function ( module
) {
2296 if ( !this.enabled
) {
2299 this.queue
.push( module
);
2300 this.requestUpdate();
2304 * Add the contents of the named module to the in-memory store.
2306 * This method does not guarantee that the module will be stored.
2307 * Inspection of the module's meta data and size will ultimately decide that.
2309 * This method is considered internal to mw.loader.store and must only
2310 * be called if the store is enabled.
2313 * @param {string} module Module name
2315 set: function ( module
) {
2318 descriptor
= mw
.loader
.moduleRegistry
[ module
];
2320 key
= getModuleKey( module
);
2323 // Already stored a copy of this exact version
2324 key
in this.items
||
2325 // Module failed to load
2327 descriptor
.state
!== 'ready' ||
2328 // Unversioned, private, or site-/user-specific
2329 !descriptor
.version
||
2330 descriptor
.group
=== 'private' ||
2331 descriptor
.group
=== 'user' ||
2332 // Partial descriptor
2333 // (e.g. skipped module, or style module with state=ready)
2334 [ descriptor
.script
, descriptor
.style
, descriptor
.messages
,
2335 descriptor
.templates
].indexOf( undefined ) !== -1
2342 if ( typeof descriptor
.script
=== 'function' ) {
2343 encodedScript
= String( descriptor
.script
);
2345 // Plain object: an object that is not null and is not an array
2346 typeof descriptor
.script
=== 'object' &&
2347 descriptor
.script
&&
2348 !Array
.isArray( descriptor
.script
)
2350 encodedScript
= '{' +
2351 '"main":' + JSON
.stringify( descriptor
.script
.main
) + ',' +
2353 Object
.keys( descriptor
.script
.files
).map( function ( key
) {
2354 var value
= descriptor
.script
.files
[ key
];
2355 return JSON
.stringify( key
) + ':' +
2356 ( typeof value
=== 'function' ? value
: JSON
.stringify( value
) );
2360 encodedScript
= JSON
.stringify( descriptor
.script
);
2363 JSON
.stringify( key
),
2365 JSON
.stringify( descriptor
.style
),
2366 JSON
.stringify( descriptor
.messages
),
2367 JSON
.stringify( descriptor
.templates
)
2370 mw
.trackError( 'resourceloader.exception', {
2372 source
: 'store-localstorage-json'
2377 src
= 'mw.loader.implement(' + args
.join( ',' ) + ');';
2378 if ( src
.length
> this.MODULE_SIZE_MAX
) {
2381 this.items
[ key
] = src
;
2385 * Iterate through the module store, removing any item that does not correspond
2386 * (in name and version) to an item in the module registry.
2388 prune: function () {
2391 for ( key
in this.items
) {
2392 module
= key
.slice( 0, key
.indexOf( '@' ) );
2393 if ( getModuleKey( module
) !== key
) {
2394 this.stats
.expired
++;
2395 delete this.items
[ key
];
2396 } else if ( this.items
[ key
].length
> this.MODULE_SIZE_MAX
) {
2397 // This value predates the enforcement of a size limit on cached modules.
2398 delete this.items
[ key
];
2404 * Clear the entire module store right now.
2406 clear: function () {
2409 localStorage
.removeItem( this.getStoreKey() );
2414 * Request a sync of the in-memory store back to persisted localStorage.
2416 * This function debounces updates. The debouncing logic should account
2417 * for the following factors:
2419 * - Writing to localStorage is an expensive operation that must not happen
2420 * during the critical path of initialising and executing module code.
2421 * Instead, it should happen at a later time after modules have been given
2422 * time and priority to do their thing first.
2424 * - This method is called from mw.loader.store.add(), which will be called
2425 * hundreds of times on a typical page, including within the same call-stack
2426 * and eventloop-tick. This is because responses from load.php happen in
2427 * batches. As such, we want to allow all modules from the same load.php
2428 * response to be written to disk with a single flush, not many.
2430 * - Repeatedly deleting and creating timers is non-trivial.
2432 * - localStorage is shared by all pages from the same origin, if multiple
2433 * pages are loaded with different module sets, the possibility exists that
2434 * modules saved by one page will be clobbered by another. The impact of
2435 * this is minor, it merely causes a less efficient cache use, and the
2436 * problem would be corrected by subsequent page views.
2438 * This method is considered internal to mw.loader.store and must only
2439 * be called if the store is enabled.
2444 requestUpdate
: ( function () {
2445 var hasPendingWrites
= false;
2447 function flushWrites() {
2450 // Remove anything from the in-memory store that came from previous page
2451 // loads that no longer corresponds with current module names and versions.
2452 mw
.loader
.store
.prune();
2453 // Process queued module names, serialise their contents to the in-memory store.
2454 while ( mw
.loader
.store
.queue
.length
) {
2455 mw
.loader
.store
.set( mw
.loader
.store
.queue
.shift() );
2458 key
= mw
.loader
.store
.getStoreKey();
2460 // Replacing the content of the module store might fail if the new
2461 // contents would exceed the browser's localStorage size limit. To
2462 // avoid clogging the browser with stale data, always remove the old
2463 // value before attempting to set the new one.
2464 localStorage
.removeItem( key
);
2465 data
= JSON
.stringify( mw
.loader
.store
);
2466 localStorage
.setItem( key
, data
);
2468 mw
.trackError( 'resourceloader.exception', {
2470 source
: 'store-localstorage-update'
2474 // Let the next call to requestUpdate() create a new timer.
2475 hasPendingWrites
= false;
2478 function onTimeout() {
2479 // Defer the actual write via requestIdleCallback
2480 mw
.requestIdleCallback( flushWrites
);
2483 return function () {
2484 // On the first call to requestUpdate(), create a timer that
2485 // waits at least two seconds, then calls onTimeout.
2486 // The main purpose is to allow the current batch of load.php
2487 // responses to complete before we do anything. This batch can
2488 // trigger many hundreds of calls to requestUpdate().
2489 if ( !hasPendingWrites
) {
2490 hasPendingWrites
= true;
2491 setTimeout( onTimeout
, 2000 );
2499 // Skeleton user object, extended by the 'mediawiki.user' module.
2506 * @property {mw.Map}
2510 * @property {mw.Map}
2515 // OOUI widgets specific to MediaWiki
2520 // Attach to window and globally alias
2521 window
.mw
= window
.mediaWiki
= mw
;