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, (or) boolean result of skip
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()
546 * 'script': closure, array of urls, or string
547 * 'style': { ... } (see #execute)
548 * 'messages': { 'key': 'value', ... }
555 * The module is known to the system but not yet required.
556 * Meta data is registered via mw.loader#register. Calls to that method are
557 * generated server-side by the startup module.
559 * The module was required through mw.loader (either directly or as dependency of
560 * another module). The client will fetch module contents from the server.
561 * The contents are then stashed in the registry via mw.loader#implement.
563 * The module has been loaded from the server and stashed via mw.loader#implement.
564 * Once the module has no more dependencies in-flight, the module will be executed,
565 * controlled via #requestPropagation and #doPropagation.
567 * The module is being executed.
569 * The module has been successfully executed.
571 * The module (or one of its dependencies) produced an error during execution.
573 * The module was registered client-side and requested, but the server denied knowledge
574 * of the module's existence.
579 var registry
= Object
.create( null ),
580 // Mapping of sources, keyed by source-id, values are strings.
585 // 'sourceId': 'http://example.org/w/load.php'
588 sources
= Object
.create( null ),
590 // For queueModuleScript()
591 handlingPendingRequests
= false,
592 pendingRequests
= [],
594 // List of modules to be loaded
598 * List of callback jobs waiting for modules to be ready.
600 * Jobs are created by #enqueue() and run by #doPropagation().
601 * Typically when a job is created for a module, the job's dependencies contain
602 * both the required module and all its recursive dependencies.
607 * 'dependencies': [ module names ],
608 * 'ready': Function callback
609 * 'error': Function callback
612 * @property {Object[]} jobs
617 // For #requestPropagation() and #doPropagation()
618 willPropagate
= false,
623 * @property {Array} baseModules
625 baseModules
= $VARS
.baseModules
,
628 * For #addEmbeddedCSS() and #addLink()
631 * @property {HTMLElement|null} marker
633 marker
= document
.querySelector( 'meta[name="ResourceLoaderDynamicStyles"]' ),
635 // For #addEmbeddedCSS()
637 rAF
= window
.requestAnimationFrame
|| setTimeout
;
640 * Create a new style element and add it to the DOM.
643 * @param {string} text CSS text
644 * @param {Node|null} [nextNode] The element where the style tag
645 * should be inserted before
646 * @return {HTMLElement} Reference to the created style element
648 function newStyleTag( text
, nextNode
) {
649 var el
= document
.createElement( 'style' );
650 el
.appendChild( document
.createTextNode( text
) );
651 if ( nextNode
&& nextNode
.parentNode
) {
652 nextNode
.parentNode
.insertBefore( el
, nextNode
);
654 document
.head
.appendChild( el
);
661 * @param {Object} cssBuffer
663 function flushCssBuffer( cssBuffer
) {
665 // Mark this object as inactive now so that further calls to addEmbeddedCSS() from
666 // the callbacks go to a new buffer instead of this one (T105973)
667 cssBuffer
.active
= false;
668 newStyleTag( cssBuffer
.cssText
, marker
);
669 for ( i
= 0; i
< cssBuffer
.callbacks
.length
; i
++ ) {
670 cssBuffer
.callbacks
[ i
]();
675 * Add a bit of CSS text to the current browser page.
677 * The creation and insertion of the `<style>` element is debounced for two reasons:
679 * - Performing the insertion before the next paint round via requestAnimationFrame
680 * avoids forced or wasted style recomputations, which are expensive in browsers.
681 * - Reduce how often new stylesheets are inserted by letting additional calls to this
682 * function accumulate into a buffer for at least one JavaScript tick. Modules are
683 * received from the server in batches, which means there is likely going to be many
684 * calls to this function in a row within the same tick / the same call stack.
688 * @param {string} cssText CSS text to be added in a `<style>` tag.
689 * @param {Function} callback Called after the insertion has occurred
691 function addEmbeddedCSS( cssText
, callback
) {
692 // Create a buffer if:
693 // - We don't have one yet.
694 // - The previous one is closed.
695 // - The next CSS chunk syntactically needs to be at the start of a stylesheet (T37562).
696 if ( !nextCssBuffer
|| nextCssBuffer
.active
=== false || cssText
.slice( 0, '@import'.length
) === '@import' ) {
704 // Linebreak for somewhat distinguishable sections
705 nextCssBuffer
.cssText
+= '\n' + cssText
;
706 nextCssBuffer
.callbacks
.push( callback
);
708 if ( nextCssBuffer
.active
=== null ) {
709 nextCssBuffer
.active
= true;
710 // The flushCssBuffer callback has its parameter bound by reference, which means
711 // 1) We can still extend the buffer from our object reference after this point.
712 // 2) We can safely re-assign the variable (not the object) to start a new buffer.
713 rAF( flushCssBuffer
.bind( null, nextCssBuffer
) );
719 * @param {string[]} modules List of module names
720 * @return {string} Hash of concatenated version hashes.
722 function getCombinedVersion( modules
) {
723 var hashes
= modules
.reduce( function ( result
, module
) {
724 return result
+ registry
[ module
].version
;
726 return fnv132( hashes
);
730 * Determine whether all dependencies are in state 'ready', which means we may
731 * execute the module or job now.
734 * @param {string[]} modules Names of modules to be checked
735 * @return {boolean} True if all modules are in state 'ready', false otherwise
737 function allReady( modules
) {
739 for ( ; i
< modules
.length
; i
++ ) {
740 if ( mw
.loader
.getState( modules
[ i
] ) !== 'ready' ) {
748 * Determine whether all direct and base dependencies are in state 'ready'
751 * @param {string} module Name of the module to be checked
752 * @return {boolean} True if all direct/base dependencies are in state 'ready'; false otherwise
754 function allWithImplicitReady( module
) {
755 return allReady( registry
[ module
].dependencies
) &&
756 ( baseModules
.indexOf( module
) !== -1 || allReady( baseModules
) );
760 * Determine whether all dependencies are in state 'ready', which means we may
761 * execute the module or job now.
764 * @param {Array} modules Names of modules to be checked
765 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
767 function anyFailed( modules
) {
770 for ( ; i
< modules
.length
; i
++ ) {
771 state
= mw
.loader
.getState( modules
[ i
] );
772 if ( state
=== 'error' || state
=== 'missing' ) {
780 * Handle propagation of module state changes and reactions to them.
782 * - When a module reaches a failure state, this should be propagated to
783 * modules that depend on the failed module.
784 * - When a module reaches a final state, pending job callbacks for the
785 * module from mw.loader.using() should be called.
786 * - When a module reaches the 'ready' state from #execute(), consider
787 * executing dependant modules now having their dependencies satisfied.
788 * - When a module reaches the 'loaded' state from mw.loader.implement,
789 * consider executing it, if it has no unsatisfied dependencies.
793 function doPropagation() {
794 var errorModule
, baseModuleError
, module
, i
, failed
, job
,
797 // Keep going until the last iteration performed no actions.
799 didPropagate
= false;
801 // Stage 1: Propagate failures
802 while ( errorModules
.length
) {
803 errorModule
= errorModules
.shift();
804 baseModuleError
= baseModules
.indexOf( errorModule
) !== -1;
805 for ( module
in registry
) {
806 if ( registry
[ module
].state
!== 'error' && registry
[ module
].state
!== 'missing' ) {
807 if ( baseModuleError
&& baseModules
.indexOf( module
) === -1 ) {
808 // Propate error from base module to all regular (non-base) modules
809 registry
[ module
].state
= 'error';
811 } else if ( registry
[ module
].dependencies
.indexOf( errorModule
) !== -1 ) {
812 // Propagate error from dependency to depending module
813 registry
[ module
].state
= 'error';
814 // .. and propagate it further
815 errorModules
.push( module
);
822 // Stage 2: Execute 'loaded' modules with no unsatisfied dependencies
823 for ( module
in registry
) {
824 if ( registry
[ module
].state
=== 'loaded' && allWithImplicitReady( module
) ) {
825 // Recursively execute all dependent modules that were already loaded
826 // (waiting for execution) and no longer have unsatisfied dependencies.
827 // Base modules may have dependencies amongst eachother to ensure correct
828 // execution order. Regular modules wait for all base modules.
829 // eslint-disable-next-line no-use-before-define
835 // Stage 3: Invoke job callbacks that are no longer blocked
836 for ( i
= 0; i
< jobs
.length
; i
++ ) {
838 failed
= anyFailed( job
.dependencies
);
839 if ( failed
|| allReady( job
.dependencies
) ) {
843 if ( failed
&& job
.error
) {
844 job
.error( new Error( 'Failed dependencies' ), job
.dependencies
);
845 } else if ( !failed
&& job
.ready
) {
849 // A user-defined callback raised an exception.
850 // Swallow it to protect our state machine!
851 mw
.trackError( 'resourceloader.exception', {
853 source
: 'load-callback'
859 } while ( didPropagate
);
861 willPropagate
= false;
865 * Request a (debounced) call to doPropagation().
869 function requestPropagation() {
870 if ( willPropagate
) {
871 // Already scheduled, or, we're already in a doPropagation stack.
874 willPropagate
= true;
875 // Yield for two reasons:
876 // * Allow successive calls to mw.loader.implement() from the same
877 // load.php response, or from the same asyncEval() to be in the
878 // propagation batch.
879 // * Allow the browser to breathe between the reception of
880 // module source code and the execution of it.
882 // Use a high priority because the user may be waiting for interactions
883 // to start being possible. But, first provide a moment (up to 'timeout')
884 // for native input event handling (e.g. scrolling/typing/clicking).
885 mw
.requestIdleCallback( doPropagation
, { timeout
: 1 } );
889 * Update a module's state in the registry and make sure any neccesary
890 * propagation will occur. See #doPropagation for more about propagation.
891 * See #registry for more about how states are used.
894 * @param {string} module
895 * @param {string} state
897 function setAndPropagate( module
, state
) {
898 registry
[ module
].state
= state
;
899 if ( state
=== 'loaded' || state
=== 'ready' || state
=== 'error' || state
=== 'missing' ) {
900 if ( state
=== 'ready' ) {
901 // Queue to later be synced to the local module store.
902 mw
.loader
.store
.add( module
);
903 } else if ( state
=== 'error' || state
=== 'missing' ) {
904 errorModules
.push( module
);
906 requestPropagation();
911 * Resolve dependencies and detect circular references.
914 * @param {string} module Name of the top-level module whose dependencies shall be
915 * resolved and sorted.
916 * @param {Array} resolved Returns a topological sort of the given module and its
917 * dependencies, such that later modules depend on earlier modules. The array
918 * contains the module names. If the array contains already some module names,
919 * this function appends its result to the pre-existing array.
920 * @param {StringSet} [unresolved] Used to track the current dependency
921 * chain, and to report loops in the dependency graph.
922 * @throws {Error} If any unregistered module or a dependency loop is encountered
924 function sortDependencies( module
, resolved
, unresolved
) {
927 if ( !( module
in registry
) ) {
928 throw new Error( 'Unknown dependency: ' + module
);
931 if ( typeof registry
[ module
].skip
=== 'string' ) {
932 // eslint-disable-next-line no-new-func
933 skip
= ( new Function( registry
[ module
].skip
)() );
934 registry
[ module
].skip
= !!skip
;
936 registry
[ module
].dependencies
= [];
937 setAndPropagate( module
, 'ready' );
942 if ( resolved
.indexOf( module
) !== -1 ) {
943 // Module already resolved; nothing to do
946 // Create unresolved if not passed in
948 unresolved
= new StringSet();
952 if ( baseModules
.indexOf( module
) === -1 ) {
953 for ( i
= 0; i
< baseModules
.length
; i
++ ) {
954 if ( resolved
.indexOf( baseModules
[ i
] ) === -1 ) {
955 resolved
.push( baseModules
[ i
] );
960 // Tracks down dependencies
961 deps
= registry
[ module
].dependencies
;
962 unresolved
.add( module
);
963 for ( i
= 0; i
< deps
.length
; i
++ ) {
964 if ( resolved
.indexOf( deps
[ i
] ) === -1 ) {
965 if ( unresolved
.has( deps
[ i
] ) ) {
967 'Circular reference detected: ' + module
+ ' -> ' + deps
[ i
]
971 sortDependencies( deps
[ i
], resolved
, unresolved
);
974 resolved
.push( module
);
978 * Get names of module that a module depends on, in their proper dependency order.
981 * @param {string[]} modules Array of string module names
982 * @return {Array} List of dependencies, including 'module'.
983 * @throws {Error} If an unregistered module or a dependency loop is encountered
985 function resolve( modules
) {
988 for ( ; i
< modules
.length
; i
++ ) {
989 sortDependencies( modules
[ i
], resolved
);
995 * Like #resolve(), except it will silently ignore modules that
996 * are missing or have missing dependencies.
999 * @param {string[]} modules Array of string module names
1000 * @return {Array} List of dependencies.
1002 function resolveStubbornly( modules
) {
1006 for ( ; i
< modules
.length
; i
++ ) {
1007 saved
= resolved
.slice();
1009 sortDependencies( modules
[ i
], resolved
);
1011 // This module is unknown or has unknown dependencies.
1012 // Undo any incomplete resolutions made and keep going.
1014 mw
.trackError( 'resourceloader.exception', {
1024 * Resolve a relative file path.
1026 * For example, resolveRelativePath( '../foo.js', 'resources/src/bar/bar.js' )
1027 * returns 'resources/src/foo.js'.
1029 * @param {string} relativePath Relative file path, starting with ./ or ../
1030 * @param {string} basePath Path of the file (not directory) relativePath is relative to
1031 * @return {string|null} Resolved path, or null if relativePath does not start with ./ or ../
1033 function resolveRelativePath( relativePath
, basePath
) {
1034 var prefixes
, prefix
, baseDirParts
,
1035 relParts
= relativePath
.match( /^((?:\.\.?\/)+)(.*)$/ );
1041 baseDirParts
= basePath
.split( '/' );
1042 // basePath looks like 'foo/bar/baz.js', so baseDirParts looks like [ 'foo', 'bar, 'baz.js' ]
1043 // Remove the file component at the end, so that we are left with only the directory path
1046 prefixes
= relParts
[ 1 ].split( '/' );
1047 // relParts[ 1 ] looks like '../../', so prefixes looks like [ '..', '..', '' ]
1048 // Remove the empty element at the end
1051 // For every ../ in the path prefix, remove one directory level from baseDirParts
1052 while ( ( prefix
= prefixes
.pop() ) !== undefined ) {
1053 if ( prefix
=== '..' ) {
1058 // If there's anything left of the base path, prepend it to the file path
1059 return ( baseDirParts
.length
? baseDirParts
.join( '/' ) + '/' : '' ) + relParts
[ 2 ];
1063 * Make a require() function scoped to a package file
1065 * @param {Object} moduleObj Module object from the registry
1066 * @param {string} basePath Path of the file this is scoped to. Used for relative paths.
1067 * @return {Function}
1069 function makeRequireFunction( moduleObj
, basePath
) {
1070 return function require( moduleName
) {
1071 var fileName
, fileContent
, result
, moduleParam
,
1072 scriptFiles
= moduleObj
.script
.files
;
1073 fileName
= resolveRelativePath( moduleName
, basePath
);
1074 if ( fileName
=== null ) {
1075 // Not a relative path, so it's a module name
1076 return mw
.loader
.require( moduleName
);
1079 if ( !hasOwn
.call( scriptFiles
, fileName
) ) {
1080 throw new Error( 'Cannot require() undefined file ' + fileName
);
1082 if ( hasOwn
.call( moduleObj
.packageExports
, fileName
) ) {
1083 // File has already been executed, return the cached result
1084 return moduleObj
.packageExports
[ fileName
];
1087 fileContent
= scriptFiles
[ fileName
];
1088 if ( typeof fileContent
=== 'function' ) {
1089 moduleParam
= { exports
: {} };
1090 fileContent( makeRequireFunction( moduleObj
, fileName
), moduleParam
);
1091 result
= moduleParam
.exports
;
1093 // fileContent is raw data, just pass it through
1094 result
= fileContent
;
1096 moduleObj
.packageExports
[ fileName
] = result
;
1102 * Load and execute a script.
1105 * @param {string} src URL to script, will be used as the src attribute in the script tag
1106 * @param {Function} [callback] Callback to run after request resolution
1108 function addScript( src
, callback
) {
1109 // Use a <script> element rather than XHR. Using XHR changes the request
1110 // headers (potentially missing a cache hit), and reduces caching in general
1111 // since browsers cache XHR much less (if at all). And XHR means we retrieve
1112 // text, so we'd need to eval, which then messes up line numbers.
1113 // The drawback is that <script> does not offer progress events, feedback is
1114 // only given after downloading, parsing, and execution have completed.
1115 var script
= document
.createElement( 'script' );
1117 script
.onload
= script
.onerror = function () {
1118 if ( script
.parentNode
) {
1119 script
.parentNode
.removeChild( script
);
1126 document
.head
.appendChild( script
);
1130 * Queue the loading and execution of a script for a particular module.
1132 * This does for debug mode what runScript() does for production.
1135 * @param {string} src URL of the script
1136 * @param {string} moduleName Name of currently executing module
1137 * @param {Function} callback Callback to run after addScript() resolution
1139 function queueModuleScript( src
, moduleName
, callback
) {
1140 pendingRequests
.push( function () {
1141 // Keep in sync with execute()/runScript().
1142 if ( moduleName
!== 'jquery' ) {
1143 window
.require
= mw
.loader
.require
;
1144 window
.module
= registry
[ moduleName
].module
;
1146 addScript( src
, function () {
1147 // 'module.exports' should not persist after the file is executed to
1148 // avoid leakage to unrelated code. 'require' should be kept, however,
1149 // as asynchronous access to 'require' is allowed and expected. (T144879)
1150 delete window
.module
;
1152 // Start the next one (if any)
1153 if ( pendingRequests
[ 0 ] ) {
1154 pendingRequests
.shift()();
1156 handlingPendingRequests
= false;
1160 if ( !handlingPendingRequests
&& pendingRequests
[ 0 ] ) {
1161 handlingPendingRequests
= true;
1162 pendingRequests
.shift()();
1167 * Utility function for execute()
1170 * @param {string} [media] Media attribute
1171 * @param {string} url URL
1173 function addLink( media
, url
) {
1174 var el
= document
.createElement( 'link' );
1176 el
.rel
= 'stylesheet';
1177 if ( media
&& media
!== 'all' ) {
1180 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1181 // see #addEmbeddedCSS, T33676, T43331, and T49277 for details.
1184 if ( marker
&& marker
.parentNode
) {
1185 marker
.parentNode
.insertBefore( el
, marker
);
1187 document
.head
.appendChild( el
);
1193 * @param {string} code JavaScript code
1195 function domEval( code
) {
1196 var script
= document
.createElement( 'script' );
1197 if ( mw
.config
.get( 'wgCSPNonce' ) !== false ) {
1198 script
.nonce
= mw
.config
.get( 'wgCSPNonce' );
1201 document
.head
.appendChild( script
);
1202 script
.parentNode
.removeChild( script
);
1206 * Add one or more modules to the module load queue.
1211 * @param {string[]} dependencies Array of module names in the registry
1212 * @param {Function} [ready] Callback to execute when all dependencies are ready
1213 * @param {Function} [error] Callback to execute when any dependency fails
1215 function enqueue( dependencies
, ready
, error
) {
1216 if ( allReady( dependencies
) ) {
1217 // Run ready immediately
1218 if ( ready
!== undefined ) {
1224 if ( anyFailed( dependencies
) ) {
1225 if ( error
!== undefined ) {
1226 // Execute error immediately if any dependencies have errors
1228 new Error( 'One or more dependencies failed to load' ),
1235 // Not all dependencies are ready, add to the load queue...
1237 // Add ready and error callbacks if they were given
1238 if ( ready
!== undefined || error
!== undefined ) {
1240 // Narrow down the list to modules that are worth waiting for
1241 dependencies
: dependencies
.filter( function ( module
) {
1242 var state
= registry
[ module
].state
;
1243 return state
=== 'registered' || state
=== 'loaded' || state
=== 'loading' || state
=== 'executing';
1250 dependencies
.forEach( function ( module
) {
1251 // Only queue modules that are still in the initial 'registered' state
1252 // (not ones already loading, ready or error).
1253 if ( registry
[ module
].state
=== 'registered' && queue
.indexOf( module
) === -1 ) {
1254 // Private modules must be embedded in the page. Don't bother queuing
1255 // these as the server will deny them anyway (T101806).
1256 if ( registry
[ module
].group
=== 'private' ) {
1257 setAndPropagate( module
, 'error' );
1259 queue
.push( module
);
1268 * Executes a loaded module, making it ready to use
1271 * @param {string} module Module name to execute
1273 function execute( module
) {
1274 var key
, value
, media
, i
, urls
, cssHandle
, siteDeps
, siteDepErr
, runScript
,
1277 if ( registry
[ module
].state
!== 'loaded' ) {
1278 throw new Error( 'Module in state "' + registry
[ module
].state
+ '" may not be executed: ' + module
);
1281 registry
[ module
].state
= 'executing';
1282 $CODE
.profileExecuteStart();
1284 runScript = function () {
1285 var script
, markModuleReady
, nestedAddScript
, mainScript
;
1287 $CODE
.profileScriptStart();
1288 script
= registry
[ module
].script
;
1289 markModuleReady = function () {
1290 $CODE
.profileScriptEnd();
1291 setAndPropagate( module
, 'ready' );
1293 nestedAddScript = function ( arr
, callback
, i
) {
1294 // Recursively call queueModuleScript() in its own callback
1295 // for each element of arr.
1296 if ( i
>= arr
.length
) {
1297 // We're at the end of the array
1302 queueModuleScript( arr
[ i
], module
, function () {
1303 nestedAddScript( arr
, callback
, i
+ 1 );
1308 if ( Array
.isArray( script
) ) {
1309 nestedAddScript( script
, markModuleReady
, 0 );
1311 typeof script
=== 'function' || (
1312 typeof script
=== 'object' &&
1316 if ( typeof script
=== 'function' ) {
1317 // Keep in sync with queueModuleScript() for debug mode
1318 if ( module
=== 'jquery' ) {
1319 // This is a special case for when 'jquery' itself is being loaded.
1320 // - The standard jquery.js distribution does not set `window.jQuery`
1321 // in CommonJS-compatible environments (Node.js, AMD, RequireJS, etc.).
1322 // - MediaWiki's 'jquery' module also bundles jquery.migrate.js, which
1323 // in a CommonJS-compatible environment, will use require('jquery'),
1324 // but that can't work when we're still inside that module.
1327 // Pass jQuery twice so that the signature of the closure which wraps
1328 // the script can bind both '$' and 'jQuery'.
1329 script( window
.$, window
.$, mw
.loader
.require
, registry
[ module
].module
);
1332 mainScript
= script
.files
[ script
.main
];
1333 if ( typeof mainScript
!== 'function' ) {
1334 throw new Error( 'Main file ' + script
.main
+ ' in module ' + module
+
1335 ' must be of type function, found ' + typeof mainScript
);
1337 // jQuery parameters are not passed for multi-file modules
1339 makeRequireFunction( registry
[ module
], script
.main
),
1340 registry
[ module
].module
1344 } else if ( typeof script
=== 'string' ) {
1345 // Site and user modules are legacy scripts that run in the global scope.
1346 // This is transported as a string instead of a function to avoid needing
1347 // to use string manipulation to undo the function wrapper.
1352 // Module without script
1356 // Use mw.track instead of mw.log because these errors are common in production mode
1357 // (e.g. undefined variable), and mw.log is only enabled in debug mode.
1358 setAndPropagate( module
, 'error' );
1359 $CODE
.profileScriptEnd();
1360 mw
.trackError( 'resourceloader.exception', {
1363 source
: 'module-execute'
1368 // Add localizations to message system
1369 if ( registry
[ module
].messages
) {
1370 mw
.messages
.set( registry
[ module
].messages
);
1373 // Initialise templates
1374 if ( registry
[ module
].templates
) {
1375 mw
.templates
.set( module
, registry
[ module
].templates
);
1378 // Adding of stylesheets is asynchronous via addEmbeddedCSS().
1379 // The below function uses a counting semaphore to make sure we don't call
1380 // runScript() until after this module's stylesheets have been inserted
1382 cssHandle = function () {
1383 // Increase semaphore, when creating a callback for addEmbeddedCSS.
1385 return function () {
1387 // Decrease semaphore, when said callback is invoked.
1389 if ( cssPending
=== 0 ) {
1391 // This callback is exposed to addEmbeddedCSS, which is outside the execute()
1392 // function and is not concerned with state-machine integrity. In turn,
1393 // addEmbeddedCSS() actually exposes stuff further into the browser (rAF).
1394 // If increment and decrement callbacks happen in the wrong order, or start
1395 // again afterwards, then this branch could be reached multiple times.
1396 // To protect the integrity of the state-machine, prevent that from happening
1397 // by making runScript() cannot be called more than once. We store a private
1398 // reference when we first reach this branch, then deference the original, and
1399 // call our reference to it.
1400 runScriptCopy
= runScript
;
1401 runScript
= undefined;
1407 // Process styles (see also mw.loader.implement)
1408 // * back-compat: { <media>: css }
1409 // * back-compat: { <media>: [url, ..] }
1410 // * { "css": [css, ..] }
1411 // * { "url": { <media>: [url, ..] } }
1412 if ( registry
[ module
].style
) {
1413 for ( key
in registry
[ module
].style
) {
1414 value
= registry
[ module
].style
[ key
];
1417 if ( key
!== 'url' && key
!== 'css' ) {
1418 // Backwards compatibility, key is a media-type
1419 if ( typeof value
=== 'string' ) {
1420 // back-compat: { <media>: css }
1421 // Ignore 'media' because it isn't supported (nor was it used).
1422 // Strings are pre-wrapped in "@media". The media-type was just ""
1423 // (because it had to be set to something).
1424 // This is one of the reasons why this format is no longer used.
1425 addEmbeddedCSS( value
, cssHandle() );
1427 // back-compat: { <media>: [url, ..] }
1433 // Array of css strings in key 'css',
1434 // or back-compat array of urls from media-type
1435 if ( Array
.isArray( value
) ) {
1436 for ( i
= 0; i
< value
.length
; i
++ ) {
1437 if ( key
=== 'bc-url' ) {
1438 // back-compat: { <media>: [url, ..] }
1439 addLink( media
, value
[ i
] );
1440 } else if ( key
=== 'css' ) {
1441 // { "css": [css, ..] }
1442 addEmbeddedCSS( value
[ i
], cssHandle() );
1445 // Not an array, but a regular object
1446 // Array of urls inside media-type key
1447 } else if ( typeof value
=== 'object' ) {
1448 // { "url": { <media>: [url, ..] } }
1449 for ( media
in value
) {
1450 urls
= value
[ media
];
1451 for ( i
= 0; i
< urls
.length
; i
++ ) {
1452 addLink( media
, urls
[ i
] );
1459 // End profiling of execute()-self before we call runScript(),
1460 // which we want to measure separately without overlap.
1461 $CODE
.profileExecuteEnd();
1463 if ( module
=== 'user' ) {
1464 // Implicit dependency on the site module. Not a real dependency because it should
1465 // run after 'site' regardless of whether it succeeds or fails.
1466 // Note: This is a simplified version of mw.loader.using(), inlined here because
1467 // mw.loader.using() is part of mediawiki.base (depends on jQuery; T192623).
1469 siteDeps
= resolve( [ 'site' ] );
1474 if ( siteDepErr
=== undefined ) {
1475 enqueue( siteDeps
, runScript
, runScript
);
1477 } else if ( cssPending
=== 0 ) {
1478 // Regular module without styles
1481 // else: runScript will get called via cssHandle()
1484 function sortQuery( o
) {
1493 for ( key
= 0; key
< a
.length
; key
++ ) {
1494 sorted
[ a
[ key
] ] = o
[ a
[ key
] ];
1500 * Converts a module map of the form `{ foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }`
1501 * to a query string of the form `foo.bar,baz|bar.baz,quux`.
1503 * See `ResourceLoader::makePackedModulesString()` in PHP, of which this is a port.
1504 * On the server, unpacking is done by `ResourceLoaderContext::expandModuleNames()`.
1506 * Note: This is only half of the logic, the other half has to be in #batchRequest(),
1507 * because its implementation needs to keep track of potential string size in order
1508 * to decide when to split the requests due to url size.
1511 * @param {Object} moduleMap Module map
1513 * @return {string} return.str Module query string
1514 * @return {Array} return.list List of module names in matching order
1516 function buildModulesString( moduleMap
) {
1521 function restore( suffix
) {
1525 for ( prefix
in moduleMap
) {
1526 p
= prefix
=== '' ? '' : prefix
+ '.';
1527 str
.push( p
+ moduleMap
[ prefix
].join( ',' ) );
1528 list
.push
.apply( list
, moduleMap
[ prefix
].map( restore
) );
1531 str
: str
.join( '|' ),
1537 * Resolve indexed dependencies.
1539 * ResourceLoader uses an optimisation to save space which replaces module names in
1540 * dependency lists with the index of that module within the array of module
1541 * registration data if it exists. The benefit is a significant reduction in the data
1542 * size of the startup module. This function changes those dependency lists back to
1543 * arrays of strings.
1546 * @param {Array} modules Modules array
1548 function resolveIndexedDependencies( modules
) {
1550 function resolveIndex( dep
) {
1551 return typeof dep
=== 'number' ? modules
[ dep
][ 0 ] : dep
;
1553 for ( i
= 0; i
< modules
.length
; i
++ ) {
1554 deps
= modules
[ i
][ 2 ];
1556 for ( j
= 0; j
< deps
.length
; j
++ ) {
1557 deps
[ j
] = resolveIndex( deps
[ j
] );
1565 * @param {Object} params Map of parameter names to values
1568 function makeQueryString( params
) {
1569 return Object
.keys( params
).map( function ( key
) {
1570 return encodeURIComponent( key
) + '=' + encodeURIComponent( params
[ key
] );
1575 * Create network requests for a batch of modules.
1577 * This is an internal method for #work(). This must not be called directly
1578 * unless the modules are already registered, and no request is in progress,
1579 * and the module state has already been set to `loading`.
1582 * @param {string[]} batch
1584 function batchRequest( batch
) {
1585 var reqBase
, splits
, b
, bSource
, bGroup
,
1586 source
, group
, i
, modules
, sourceLoadScript
,
1587 currReqBase
, currReqBaseLength
, moduleMap
, currReqModules
, l
,
1588 lastDotIndex
, prefix
, suffix
, bytesAdded
;
1591 * Start the currently drafted request to the server.
1595 function doRequest() {
1596 // Optimisation: Inherit (Object.create), not copy ($.extend)
1597 var query
= Object
.create( currReqBase
),
1598 packed
= buildModulesString( moduleMap
);
1599 query
.modules
= packed
.str
;
1600 // The packing logic can change the effective order, even if the input was
1601 // sorted. As such, the call to getCombinedVersion() must use this
1602 // effective order, instead of currReqModules, as otherwise the combined
1603 // version will not match the hash expected by the server based on
1604 // combining versions from the module query string in-order. (T188076)
1605 query
.version
= getCombinedVersion( packed
.list
);
1606 query
= sortQuery( query
);
1607 addScript( sourceLoadScript
+ '?' + makeQueryString( query
) );
1610 if ( !batch
.length
) {
1614 // Always order modules alphabetically to help reduce cache
1615 // misses for otherwise identical content.
1618 // Query parameters common to all requests
1620 skin
: mw
.config
.get( 'skin' ),
1621 lang
: mw
.config
.get( 'wgUserLanguage' ),
1622 debug
: mw
.config
.get( 'debug' )
1625 // Split module list by source and by group.
1626 splits
= Object
.create( null );
1627 for ( b
= 0; b
< batch
.length
; b
++ ) {
1628 bSource
= registry
[ batch
[ b
] ].source
;
1629 bGroup
= registry
[ batch
[ b
] ].group
;
1630 if ( !splits
[ bSource
] ) {
1631 splits
[ bSource
] = Object
.create( null );
1633 if ( !splits
[ bSource
][ bGroup
] ) {
1634 splits
[ bSource
][ bGroup
] = [];
1636 splits
[ bSource
][ bGroup
].push( batch
[ b
] );
1639 for ( source
in splits
) {
1640 sourceLoadScript
= sources
[ source
];
1642 for ( group
in splits
[ source
] ) {
1644 // Cache access to currently selected list of
1645 // modules for this group from this source.
1646 modules
= splits
[ source
][ group
];
1648 // Query parameters common to requests for this module group
1649 // Optimisation: Inherit (Object.create), not copy ($.extend)
1650 currReqBase
= Object
.create( reqBase
);
1651 // User modules require a user name in the query string.
1652 if ( group
=== 'user' && mw
.config
.get( 'wgUserName' ) !== null ) {
1653 currReqBase
.user
= mw
.config
.get( 'wgUserName' );
1656 // In addition to currReqBase, doRequest() will also add 'modules' and 'version'.
1657 // > '&modules='.length === 9
1658 // > '&version=1234567'.length === 16
1660 currReqBaseLength
= makeQueryString( currReqBase
).length
+ 25;
1662 // We may need to split up the request to honor the query string length limit,
1663 // so build it piece by piece.
1664 l
= currReqBaseLength
;
1665 moduleMap
= Object
.create( null ); // { prefix: [ suffixes ] }
1666 currReqModules
= [];
1668 for ( i
= 0; i
< modules
.length
; i
++ ) {
1669 // Determine how many bytes this module would add to the query string
1670 lastDotIndex
= modules
[ i
].lastIndexOf( '.' );
1671 // If lastDotIndex is -1, substr() returns an empty string
1672 prefix
= modules
[ i
].substr( 0, lastDotIndex
);
1673 suffix
= modules
[ i
].slice( lastDotIndex
+ 1 );
1674 bytesAdded
= moduleMap
[ prefix
] ?
1675 suffix
.length
+ 3 : // '%2C'.length == 3
1676 modules
[ i
].length
+ 3; // '%7C'.length == 3
1678 // If the url would become too long, create a new one, but don't create empty requests
1679 if ( currReqModules
.length
&& l
+ bytesAdded
> mw
.loader
.maxQueryLength
) {
1680 // Dispatch what we've got...
1682 // .. and start again.
1683 l
= currReqBaseLength
;
1684 moduleMap
= Object
.create( null );
1685 currReqModules
= [];
1687 mw
.track( 'resourceloader.splitRequest', { maxQueryLength
: mw
.loader
.maxQueryLength
} );
1689 if ( !moduleMap
[ prefix
] ) {
1690 moduleMap
[ prefix
] = [];
1693 moduleMap
[ prefix
].push( suffix
);
1694 currReqModules
.push( modules
[ i
] );
1696 // If there's anything left in moduleMap, request that too
1697 if ( currReqModules
.length
) {
1706 * @param {string[]} implementations Array containing pieces of JavaScript code in the
1707 * form of calls to mw.loader#implement().
1708 * @param {Function} cb Callback in case of failure
1709 * @param {Error} cb.err
1711 function asyncEval( implementations
, cb
) {
1712 if ( !implementations
.length
) {
1715 mw
.requestIdleCallback( function () {
1717 domEval( implementations
.join( ';' ) );
1725 * Make a versioned key for a specific module.
1728 * @param {string} module Module name
1729 * @return {string|null} Module key in format '`[name]@[version]`',
1730 * or null if the module does not exist
1732 function getModuleKey( module
) {
1733 return module
in registry
? ( module
+ '@' + registry
[ module
].version
) : null;
1738 * @param {string} key Module name or '`[name]@[version]`'
1741 function splitModuleKey( key
) {
1742 var index
= key
.indexOf( '@' );
1743 if ( index
=== -1 ) {
1750 name
: key
.slice( 0, index
),
1751 version
: key
.slice( index
+ 1 )
1757 * @param {string} module
1758 * @param {string|number} [version]
1759 * @param {string[]} [dependencies]
1760 * @param {string} [group]
1761 * @param {string} [source]
1762 * @param {string} [skip]
1764 function registerOne( module
, version
, dependencies
, group
, source
, skip
) {
1765 if ( module
in registry
) {
1766 throw new Error( 'module already registered: ' + module
);
1768 registry
[ module
] = {
1769 // Exposed to execute() for mw.loader.implement() closures.
1770 // Import happens via require().
1774 // module.export objects for each package file inside this module
1776 version
: String( version
|| '' ),
1777 dependencies
: dependencies
|| [],
1778 group
: typeof group
=== 'string' ? group
: null,
1779 source
: typeof source
=== 'string' ? source
: 'local',
1780 state
: 'registered',
1781 skip
: typeof skip
=== 'string' ? skip
: null
1785 /* Public Members */
1788 * The module registry is exposed as an aid for debugging and inspecting page
1789 * state; it is not a public interface for modifying the registry.
1795 moduleRegistry
: registry
,
1798 * Exposed for testing and debugging only.
1800 * @see #batchRequest
1804 maxQueryLength
: $VARS
.maxQueryLength
,
1807 * @inheritdoc #newStyleTag
1810 addStyleTag
: newStyleTag
,
1817 * Start loading of all queued module dependencies.
1822 var implementations
, sourceModules
,
1826 // Appends a list of modules from the queue to the batch
1827 for ( ; q
< queue
.length
; q
++ ) {
1828 // Only load modules which are registered
1829 if ( queue
[ q
] in registry
&& registry
[ queue
[ q
] ].state
=== 'registered' ) {
1830 // Prevent duplicate entries
1831 if ( batch
.indexOf( queue
[ q
] ) === -1 ) {
1832 batch
.push( queue
[ q
] );
1833 // Mark registered modules as loading
1834 registry
[ queue
[ q
] ].state
= 'loading';
1839 // Now that the queue has been processed into a batch, clear the queue.
1840 // This MUST happen before we initiate any eval or network request. Otherwise,
1841 // it is possible for a cached script to instantly trigger the same work queue
1842 // again; all before we've cleared it causing each request to include modules
1843 // which are already loaded.
1846 if ( !batch
.length
) {
1850 mw
.loader
.store
.init();
1851 if ( mw
.loader
.store
.enabled
) {
1852 implementations
= [];
1854 batch
= batch
.filter( function ( module
) {
1855 var implementation
= mw
.loader
.store
.get( module
);
1856 if ( implementation
) {
1857 implementations
.push( implementation
);
1858 sourceModules
.push( module
);
1863 asyncEval( implementations
, function ( err
) {
1865 // Not good, the cached mw.loader.implement calls failed! This should
1866 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1867 // Depending on how corrupt the string is, it is likely that some
1868 // modules' implement() succeeded while the ones after the error will
1869 // never run and leave their modules in the 'loading' state forever.
1870 mw
.loader
.store
.stats
.failed
++;
1872 // Since this is an error not caused by an individual module but by
1873 // something that infected the implement call itself, don't take any
1874 // risks and clear everything in this cache.
1875 mw
.loader
.store
.clear();
1877 mw
.trackError( 'resourceloader.exception', {
1879 source
: 'store-eval'
1881 // Re-add the failed ones that are still pending back to the batch
1882 failed
= sourceModules
.filter( function ( module
) {
1883 return registry
[ module
].state
=== 'loading';
1885 batchRequest( failed
);
1889 batchRequest( batch
);
1893 * Register a source.
1895 * The #work() method will use this information to split up requests by source.
1897 * mw.loader.addSource( { mediawikiwiki: 'https://www.mediawiki.org/w/load.php' } );
1900 * @param {Object} ids An object mapping ids to load.php end point urls
1901 * @throws {Error} If source id is already registered
1903 addSource: function ( ids
) {
1906 if ( id
in sources
) {
1907 throw new Error( 'source already registered: ' + id
);
1909 sources
[ id
] = ids
[ id
];
1914 * Register a module, letting the system know about it and its properties.
1916 * The startup module calls this method.
1918 * When using multiple module registration by passing an array, dependencies that
1919 * are specified as references to modules within the array will be resolved before
1920 * the modules are registered.
1922 * @param {string|Array} modules Module name or array of arrays, each containing
1923 * a list of arguments compatible with this method
1924 * @param {string|number} [version] Module version hash (falls backs to empty string)
1925 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1926 * @param {string[]} [dependencies] Array of module names on which this module depends.
1927 * @param {string} [group=null] Group which the module is in
1928 * @param {string} [source='local'] Name of the source
1929 * @param {string} [skip=null] Script body of the skip function
1931 register: function ( modules
) {
1933 if ( typeof modules
=== 'object' ) {
1934 resolveIndexedDependencies( modules
);
1935 // Optimisation: Up to 55% faster.
1936 // Typically called only once, and with a batch.
1937 // See <https://gist.github.com/Krinkle/f06fdb3de62824c6c16f02a0e6ce0e66>
1938 // Benchmarks taught us that the code for adding an object to `registry`
1939 // should actually be inline, or in a simple function that does no
1940 // arguments manipulation, and isn't also the caller itself.
1941 // JS semantics make it hard to optimise recursion to a different
1942 // signature of itself.
1943 for ( i
= 0; i
< modules
.length
; i
++ ) {
1944 registerOne
.apply( null, modules
[ i
] );
1947 registerOne
.apply( null, arguments
);
1952 * Implement a module given the components that make up the module.
1954 * When #load() or #using() requests one or more modules, the server
1955 * response contain calls to this function.
1957 * @param {string} module Name of module and current module version. Formatted
1958 * as '`[name]@[version]`". This version should match the requested version
1959 * (from #batchRequest and #registry). This avoids race conditions (T117587).
1960 * For back-compat with MediaWiki 1.27 and earlier, the version may be omitted.
1961 * @param {Function|Array|string|Object} [script] Module code. This can be a function,
1962 * a list of URLs to load via `<script src>`, a string for `$.globalEval()`, or an
1963 * object like {"files": {"foo.js":function, "bar.js": function, ...}, "main": "foo.js"}.
1964 * If an object is provided, the main file will be executed immediately, and the other
1965 * files will only be executed if loaded via require(). If a function or string is
1966 * provided, it will be executed/evaluated immediately. If an array is provided, all
1967 * URLs in the array will be loaded immediately, and executed as soon as they arrive.
1968 * @param {Object} [style] Should follow one of the following patterns:
1970 * { "css": [css, ..] }
1971 * { "url": { <media>: [url, ..] } }
1973 * And for backwards compatibility (needs to be supported forever due to caching):
1976 * { <media>: [url, ..] }
1978 * The reason css strings are not concatenated anymore is T33676. We now check
1979 * whether it's safe to extend the stylesheet.
1982 * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1983 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1985 implement: function ( module
, script
, style
, messages
, templates
) {
1986 var split
= splitModuleKey( module
),
1988 version
= split
.version
;
1989 // Automatically register module
1990 if ( !( name
in registry
) ) {
1991 mw
.loader
.register( name
);
1993 // Check for duplicate implementation
1994 if ( registry
[ name
].script
!== undefined ) {
1995 throw new Error( 'module already implemented: ' + name
);
1998 // Without this reset, if there is a version mismatch between the
1999 // requested and received module version, then mw.loader.store would
2000 // cache the response under the requested key. Thus poisoning the cache
2001 // indefinitely with a stale value. (T117587)
2002 registry
[ name
].version
= version
;
2004 // Attach components
2005 registry
[ name
].script
= script
|| null;
2006 registry
[ name
].style
= style
|| null;
2007 registry
[ name
].messages
= messages
|| null;
2008 registry
[ name
].templates
= templates
|| null;
2009 // The module may already have been marked as erroneous
2010 if ( registry
[ name
].state
!== 'error' && registry
[ name
].state
!== 'missing' ) {
2011 setAndPropagate( name
, 'loaded' );
2016 * Load an external script or one or more modules.
2018 * This method takes a list of unrelated modules. Use cases:
2020 * - A web page will be composed of many different widgets. These widgets independently
2021 * queue their ResourceLoader modules (`OutputPage::addModules()`). If any of them
2022 * have problems, or are no longer known (e.g. cached HTML), the other modules
2023 * should still be loaded.
2024 * - This method is used for preloading, which must not throw. Later code that
2025 * calls #using() will handle the error.
2027 * @param {string|Array} modules Either the name of a module, array of modules,
2028 * or a URL of an external script or style
2029 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
2030 * external script or style; acceptable values are "text/css" and
2031 * "text/javascript"; if no type is provided, text/javascript is assumed.
2033 load: function ( modules
, type
) {
2036 // Allow calling with a url or single dependency as a string
2037 if ( typeof modules
=== 'string' ) {
2038 // "https://example.org/x.js", "http://example.org/x.js", "//example.org/x.js", "/x.js"
2039 if ( /^(https?:)?\/?\//.test( modules
) ) {
2040 if ( type
=== 'text/css' ) {
2041 l
= document
.createElement( 'link' );
2042 l
.rel
= 'stylesheet';
2044 document
.head
.appendChild( l
);
2047 if ( type
=== 'text/javascript' || type
=== undefined ) {
2048 addScript( modules
);
2052 throw new Error( 'type must be text/css or text/javascript, found ' + type
);
2054 // Called with single module
2055 modules
= [ modules
];
2058 // Filter out top-level modules that are unknown or failed to load before.
2059 filtered
= modules
.filter( function ( module
) {
2060 var state
= mw
.loader
.getState( module
);
2061 return state
!== 'error' && state
!== 'missing';
2063 // Resolve remaining list using the known dependency tree.
2064 // This also filters out modules with unknown dependencies. (T36853)
2065 filtered
= resolveStubbornly( filtered
);
2066 // Some modules are not yet ready, add to module load queue.
2067 enqueue( filtered
, undefined, undefined );
2071 * Change the state of one or more modules.
2073 * @param {Object} states Object of module name/state pairs
2075 state: function ( states
) {
2077 for ( module
in states
) {
2078 state
= states
[ module
];
2079 if ( !( module
in registry
) ) {
2080 mw
.loader
.register( module
);
2082 setAndPropagate( module
, state
);
2087 * Get the version of a module.
2089 * @param {string} module Name of module
2090 * @return {string|null} The version, or null if the module (or its version) is not
2093 getVersion: function ( module
) {
2094 return module
in registry
? registry
[ module
].version
: null;
2098 * Get the state of a module.
2100 * @param {string} module Name of module
2101 * @return {string|null} The state, or null if the module (or its state) is not
2104 getState: function ( module
) {
2105 return module
in registry
? registry
[ module
].state
: null;
2109 * Get the names of all registered modules.
2113 getModuleNames: function () {
2114 return Object
.keys( registry
);
2118 * Get the exported value of a module.
2120 * This static method is publicly exposed for debugging purposes
2121 * only and must not be used in production code. In production code,
2122 * please use the dynamically provided `require()` function instead.
2124 * In case of lazy-loaded modules via mw.loader#using(), the returned
2125 * Promise provides the function, see #using() for examples.
2129 * @param {string} moduleName Module name
2130 * @return {Mixed} Exported value
2132 require: function ( moduleName
) {
2133 var state
= mw
.loader
.getState( moduleName
);
2135 // Only ready modules can be required
2136 if ( state
!== 'ready' ) {
2137 // Module may've forgotten to declare a dependency
2138 throw new Error( 'Module "' + moduleName
+ '" is not loaded' );
2141 return registry
[ moduleName
].module
.exports
;
2145 * On browsers that implement the localStorage API, the module store serves as a
2146 * smart complement to the browser cache. Unlike the browser cache, the module store
2147 * can slice a concatenated response from ResourceLoader into its constituent
2148 * modules and cache each of them separately, using each module's versioning scheme
2149 * to determine when the cache should be invalidated.
2153 * @class mw.loader.store
2156 // Whether the store is in use on this page.
2159 // Modules whose string representation exceeds 100 kB are
2160 // ineligible for storage. See bug T66721.
2161 MODULE_SIZE_MAX
: 100 * 1000,
2163 // The contents of the store, mapping '[name]@[version]' keys
2164 // to module implementations.
2167 // Names of modules to be stored during the next update.
2168 // See add() and update().
2172 stats
: { hits
: 0, misses
: 0, expired
: 0, failed
: 0 },
2175 * Construct a JSON-serializable object representing the content of the store.
2177 * @return {Object} Module store contents.
2179 toJSON: function () {
2180 return { items
: mw
.loader
.store
.items
, vary
: mw
.loader
.store
.getVary() };
2184 * Get the localStorage key for the entire module store. The key references
2185 * $wgDBname to prevent clashes between wikis which share a common host.
2187 * @return {string} localStorage item key
2189 getStoreKey: function () {
2190 return 'MediaWikiModuleStore:' + mw
.config
.get( 'wgDBname' );
2194 * Get a key on which to vary the module cache.
2196 * @return {string} String of concatenated vary conditions.
2198 getVary: function () {
2199 return mw
.config
.get( 'skin' ) + ':' +
2200 mw
.config
.get( 'wgResourceLoaderStorageVersion' ) + ':' +
2201 mw
.config
.get( 'wgUserLanguage' );
2205 * Initialize the store.
2207 * Retrieves store from localStorage and (if successfully retrieved) decoding
2208 * the stored JSON value to a plain object.
2210 * The try / catch block is used for JSON & localStorage feature detection.
2211 * See the in-line documentation for Modernizr's localStorage feature detection
2212 * code for a full account of why we need a try / catch:
2213 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2218 if ( this.enabled
!== null ) {
2224 // Disabled because localStorage quotas are tight and (in Firefox's case)
2225 // shared by multiple origins.
2226 // See T66721, and <https://bugzilla.mozilla.org/show_bug.cgi?id=1064466>.
2227 /Firefox/.test( navigator
.userAgent
) ||
2229 // Disabled by configuration.
2230 !mw
.config
.get( 'wgResourceLoaderStorageEnabled' )
2232 // Clear any previous store to free up space. (T66721)
2234 this.enabled
= false;
2237 if ( mw
.config
.get( 'debug' ) ) {
2238 // Disable module store in debug mode
2239 this.enabled
= false;
2244 // This a string we stored, or `null` if the key does not (yet) exist.
2245 raw
= localStorage
.getItem( this.getStoreKey() );
2246 // If we get here, localStorage is available; mark enabled
2247 this.enabled
= true;
2248 // If null, JSON.parse() will cast to string and re-parse, still null.
2249 data
= JSON
.parse( raw
);
2250 if ( data
&& typeof data
.items
=== 'object' && data
.vary
=== this.getVary() ) {
2251 this.items
= data
.items
;
2255 // Perhaps localStorage was disabled by the user, or got corrupted.
2256 // See point 3 and 4 below. (T195647)
2259 // If we get here, one of four things happened:
2261 // 1. localStorage did not contain our store key.
2262 // This means `raw` is `null`, and we're on a fresh page view (cold cache).
2263 // The store was enabled, and `items` starts fresh.
2265 // 2. localStorage contained parseable data under our store key,
2266 // but it's not applicable to our current context (see getVary).
2267 // The store was enabled, and `items` starts fresh.
2269 // 3. JSON.parse threw (localStorage contained corrupt data).
2270 // This means `raw` contains a string.
2271 // The store was enabled, and `items` starts fresh.
2273 // 4. localStorage threw (disabled or otherwise unavailable).
2274 // This means `raw` was never assigned.
2275 // We will disable the store below.
2276 if ( raw
=== undefined ) {
2277 // localStorage failed; disable store
2278 this.enabled
= false;
2283 * Retrieve a module from the store and update cache hit stats.
2285 * @param {string} module Module name
2286 * @return {string|boolean} Module implementation or false if unavailable
2288 get: function ( module
) {
2291 if ( !this.enabled
) {
2295 key
= getModuleKey( module
);
2296 if ( key
in this.items
) {
2298 return this.items
[ key
];
2301 this.stats
.misses
++;
2306 * Queue the name of a module that the next update should consider storing.
2309 * @param {string} module Module name
2311 add: function ( module
) {
2312 if ( !this.enabled
) {
2315 this.queue
.push( module
);
2316 this.requestUpdate();
2320 * Add the contents of the named module to the in-memory store.
2322 * This method does not guarantee that the module will be stored.
2323 * Inspection of the module's meta data and size will ultimately decide that.
2325 * This method is considered internal to mw.loader.store and must only
2326 * be called if the store is enabled.
2329 * @param {string} module Module name
2331 set: function ( module
) {
2334 descriptor
= mw
.loader
.moduleRegistry
[ module
];
2336 key
= getModuleKey( module
);
2339 // Already stored a copy of this exact version
2340 key
in this.items
||
2341 // Module failed to load
2343 descriptor
.state
!== 'ready' ||
2344 // Unversioned, private, or site-/user-specific
2345 !descriptor
.version
||
2346 descriptor
.group
=== 'private' ||
2347 descriptor
.group
=== 'user' ||
2348 // Partial descriptor
2349 // (e.g. skipped module, or style module with state=ready)
2350 [ descriptor
.script
, descriptor
.style
, descriptor
.messages
,
2351 descriptor
.templates
].indexOf( undefined ) !== -1
2358 if ( typeof descriptor
.script
=== 'function' ) {
2359 // Function literal: cast to string
2360 encodedScript
= String( descriptor
.script
);
2362 // Plain object: serialise as object literal (not JSON),
2363 // making sure to preserve the functions.
2364 typeof descriptor
.script
=== 'object' &&
2365 descriptor
.script
&&
2366 !Array
.isArray( descriptor
.script
)
2368 encodedScript
= '{' +
2369 'main:' + JSON
.stringify( descriptor
.script
.main
) + ',' +
2371 Object
.keys( descriptor
.script
.files
).map( function ( key
) {
2372 var value
= descriptor
.script
.files
[ key
];
2373 return JSON
.stringify( key
) + ':' +
2374 ( typeof value
=== 'function' ? value
: JSON
.stringify( value
) );
2378 // Array of urls, or null.
2379 encodedScript
= JSON
.stringify( descriptor
.script
);
2382 JSON
.stringify( key
),
2384 JSON
.stringify( descriptor
.style
),
2385 JSON
.stringify( descriptor
.messages
),
2386 JSON
.stringify( descriptor
.templates
)
2389 mw
.trackError( 'resourceloader.exception', {
2391 source
: 'store-localstorage-json'
2396 src
= 'mw.loader.implement(' + args
.join( ',' ) + ');';
2397 if ( src
.length
> this.MODULE_SIZE_MAX
) {
2400 this.items
[ key
] = src
;
2404 * Iterate through the module store, removing any item that does not correspond
2405 * (in name and version) to an item in the module registry.
2407 prune: function () {
2410 for ( key
in this.items
) {
2411 module
= key
.slice( 0, key
.indexOf( '@' ) );
2412 if ( getModuleKey( module
) !== key
) {
2413 this.stats
.expired
++;
2414 delete this.items
[ key
];
2415 } else if ( this.items
[ key
].length
> this.MODULE_SIZE_MAX
) {
2416 // This value predates the enforcement of a size limit on cached modules.
2417 delete this.items
[ key
];
2423 * Clear the entire module store right now.
2425 clear: function () {
2428 localStorage
.removeItem( this.getStoreKey() );
2433 * Request a sync of the in-memory store back to persisted localStorage.
2435 * This function debounces updates. The debouncing logic should account
2436 * for the following factors:
2438 * - Writing to localStorage is an expensive operation that must not happen
2439 * during the critical path of initialising and executing module code.
2440 * Instead, it should happen at a later time after modules have been given
2441 * time and priority to do their thing first.
2443 * - This method is called from mw.loader.store.add(), which will be called
2444 * hundreds of times on a typical page, including within the same call-stack
2445 * and eventloop-tick. This is because responses from load.php happen in
2446 * batches. As such, we want to allow all modules from the same load.php
2447 * response to be written to disk with a single flush, not many.
2449 * - Repeatedly deleting and creating timers is non-trivial.
2451 * - localStorage is shared by all pages from the same origin, if multiple
2452 * pages are loaded with different module sets, the possibility exists that
2453 * modules saved by one page will be clobbered by another. The impact of
2454 * this is minor, it merely causes a less efficient cache use, and the
2455 * problem would be corrected by subsequent page views.
2457 * This method is considered internal to mw.loader.store and must only
2458 * be called if the store is enabled.
2463 requestUpdate
: ( function () {
2464 var hasPendingWrites
= false;
2466 function flushWrites() {
2469 // Remove anything from the in-memory store that came from previous page
2470 // loads that no longer corresponds with current module names and versions.
2471 mw
.loader
.store
.prune();
2472 // Process queued module names, serialise their contents to the in-memory store.
2473 while ( mw
.loader
.store
.queue
.length
) {
2474 mw
.loader
.store
.set( mw
.loader
.store
.queue
.shift() );
2477 key
= mw
.loader
.store
.getStoreKey();
2479 // Replacing the content of the module store might fail if the new
2480 // contents would exceed the browser's localStorage size limit. To
2481 // avoid clogging the browser with stale data, always remove the old
2482 // value before attempting to set the new one.
2483 localStorage
.removeItem( key
);
2484 data
= JSON
.stringify( mw
.loader
.store
);
2485 localStorage
.setItem( key
, data
);
2487 mw
.trackError( 'resourceloader.exception', {
2489 source
: 'store-localstorage-update'
2493 // Let the next call to requestUpdate() create a new timer.
2494 hasPendingWrites
= false;
2497 function onTimeout() {
2498 // Defer the actual write via requestIdleCallback
2499 mw
.requestIdleCallback( flushWrites
);
2502 return function () {
2503 // On the first call to requestUpdate(), create a timer that
2504 // waits at least two seconds, then calls onTimeout.
2505 // The main purpose is to allow the current batch of load.php
2506 // responses to complete before we do anything. This batch can
2507 // trigger many hundreds of calls to requestUpdate().
2508 if ( !hasPendingWrites
) {
2509 hasPendingWrites
= true;
2510 setTimeout( onTimeout
, 2000 );
2518 // Skeleton user object, extended by the 'mediawiki.user' module.
2525 * @property {mw.Map}
2529 * @property {mw.Map}
2534 // OOUI widgets specific to MediaWiki
2539 // Attach to window and globally alias
2540 window
.mw
= window
.mediaWiki
= mw
;