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
.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 ).slice( 0, 5 );
41 while ( hash
.length
< 5 ) {
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
: window
.QUnit
&& defineFallbacks
,
367 * Get the current time, measured in milliseconds since January 1, 1970 (UTC).
369 * On browsers that implement the Navigation Timing API, this function will produce
370 * floating-point values with microsecond precision that are guaranteed to be monotonic.
371 * On all other browsers, it will fall back to using `Date`.
373 * @return {number} Current time
376 // Optimisation: Make startup initialisation faster by defining the
377 // shortcut on first call, not at module definition.
378 var perf
= window
.performance
,
379 navStart
= perf
&& perf
.timing
&& perf
.timing
.navigationStart
;
381 // Define the relevant shortcut
382 mw
.now
= navStart
&& perf
.now
?
383 function () { return navStart
+ perf
.now(); } :
390 * List of all analytic events emitted so far.
392 * Exposed only for use by mediawiki.base.
399 track: function ( topic
, data
) {
400 mw
.trackQueue
.push( { topic
: topic
, timeStamp
: mw
.now(), data
: data
} );
401 // This method is extended by mediawiki.base to also fire events.
405 * Track an early error event via mw.track and send it to the window console.
408 * @param {string} topic Topic name
409 * @param {Object} data Data describing the event, encoded as an object; see mw#logError
411 trackError: function ( topic
, data
) {
412 mw
.track( topic
, data
);
413 logError( topic
, data
);
416 // Expose Map constructor
420 * Map of configuration values.
422 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
425 * If `$wgLegacyJavaScriptGlobals` is true, this Map will add its values to the
426 * global `window` object.
428 * @property {mw.Map} config
430 config
: new Map( $VARS
.wgLegacyJavaScriptGlobals
),
433 * Store for messages.
440 * Store for templates associated with a module.
444 templates
: new Map(),
450 * Client for ResourceLoader server end point.
452 * This client is in charge of maintaining the module registry and state
453 * machine, initiating network (batch) requests for loading modules, as
454 * well as dependency resolution and execution of source code.
456 * For more information, refer to
457 * <https://www.mediawiki.org/wiki/ResourceLoader/Features>
462 loader
: ( function () {
465 * Fired via mw.track on various resource loading errors.
467 * @event resourceloader_exception
468 * @param {Error|Mixed} e The error that was thrown. Almost always an Error
469 * object, but in theory module code could manually throw something else, and that
470 * might also end up here.
471 * @param {string} [module] Name of the module which caused the error. Omitted if the
472 * error is not module-related or the module cannot be easily identified due to
474 * @param {string} source Source of the error. Possible values:
476 * - style: stylesheet error (only affects old IE where a special style loading method
478 * - load-callback: exception thrown by user callback
479 * - module-execute: exception thrown by module code
480 * - resolve: failed to sort dependencies for a module in mw.loader.load
481 * - store-eval: could not evaluate module code cached in localStorage
482 * - store-localstorage-init: localStorage or JSON parse error in mw.loader.store.init
483 * - store-localstorage-json: JSON conversion error in mw.loader.store
484 * - store-localstorage-update: localStorage conversion error in mw.loader.store.
488 * Fired via mw.track on resource loading error conditions.
490 * @event resourceloader_assert
491 * @param {string} source Source of the error. Possible values:
493 * - bug-T59567: failed to cache script due to an Opera function -> string conversion
494 * bug; see <https://phabricator.wikimedia.org/T59567> for details
498 * Mapping of registered modules.
500 * See #implement and #execute for exact details on support for script, style and messages.
506 * // From mw.loader.register()
507 * 'version': '########' (hash)
508 * 'dependencies': ['required.foo', 'bar.also', ...]
509 * 'group': string, integer, (or) null
510 * 'source': 'local', (or) 'anotherwiki'
511 * 'skip': 'return !!window.Example', (or) null, (or) boolean result of skip
512 * 'module': export Object
514 * // Set from execute() or mw.loader.state()
515 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error', or 'missing'
517 * // Optionally added at run-time by mw.loader.implement()
518 * 'script': closure, array of urls, or string
519 * 'style': { ... } (see #execute)
520 * 'messages': { 'key': 'value', ... }
527 * The module is known to the system but not yet required.
528 * Meta data is registered via mw.loader#register. Calls to that method are
529 * generated server-side by the startup module.
531 * The module was required through mw.loader (either directly or as dependency of
532 * another module). The client will fetch module contents from the server.
533 * The contents are then stashed in the registry via mw.loader#implement.
535 * The module has been loaded from the server and stashed via mw.loader#implement.
536 * Once the module has no more dependencies in-flight, the module will be executed,
537 * controlled via #requestPropagation and #doPropagation.
539 * The module is being executed.
541 * The module has been successfully executed.
543 * The module (or one of its dependencies) produced an error during execution.
545 * The module was registered client-side and requested, but the server denied knowledge
546 * of the module's existence.
551 var registry
= Object
.create( null ),
552 // Mapping of sources, keyed by source-id, values are strings.
557 // 'sourceId': 'http://example.org/w/load.php'
560 sources
= Object
.create( null ),
562 // For queueModuleScript()
563 handlingPendingRequests
= false,
564 pendingRequests
= [],
566 // List of modules to be loaded
570 * List of callback jobs waiting for modules to be ready.
572 * Jobs are created by #enqueue() and run by #doPropagation().
573 * Typically when a job is created for a module, the job's dependencies contain
574 * both the required module and all its recursive dependencies.
579 * 'dependencies': [ module names ],
580 * 'ready': Function callback
581 * 'error': Function callback
584 * @property {Object[]} jobs
589 // For #requestPropagation() and #doPropagation()
590 willPropagate
= false,
595 * @property {Array} baseModules
597 baseModules
= $VARS
.baseModules
,
600 * For #addEmbeddedCSS() and #addLink()
603 * @property {HTMLElement|null} marker
605 marker
= document
.querySelector( 'meta[name="ResourceLoaderDynamicStyles"]' ),
607 // For #addEmbeddedCSS()
609 rAF
= window
.requestAnimationFrame
|| setTimeout
;
612 * Create a new style element and add it to the DOM.
615 * @param {string} text CSS text
616 * @param {Node|null} [nextNode] The element where the style tag
617 * should be inserted before
618 * @return {HTMLElement} Reference to the created style element
620 function newStyleTag( text
, nextNode
) {
621 var el
= document
.createElement( 'style' );
622 el
.appendChild( document
.createTextNode( text
) );
623 if ( nextNode
&& nextNode
.parentNode
) {
624 nextNode
.parentNode
.insertBefore( el
, nextNode
);
626 document
.head
.appendChild( el
);
633 * @param {Object} cssBuffer
635 function flushCssBuffer( cssBuffer
) {
637 // Mark this object as inactive now so that further calls to addEmbeddedCSS() from
638 // the callbacks go to a new buffer instead of this one (T105973)
639 cssBuffer
.active
= false;
640 newStyleTag( cssBuffer
.cssText
, marker
);
641 for ( i
= 0; i
< cssBuffer
.callbacks
.length
; i
++ ) {
642 cssBuffer
.callbacks
[ i
]();
647 * Add a bit of CSS text to the current browser page.
649 * The creation and insertion of the `<style>` element is debounced for two reasons:
651 * - Performing the insertion before the next paint round via requestAnimationFrame
652 * avoids forced or wasted style recomputations, which are expensive in browsers.
653 * - Reduce how often new stylesheets are inserted by letting additional calls to this
654 * function accumulate into a buffer for at least one JavaScript tick. Modules are
655 * received from the server in batches, which means there is likely going to be many
656 * calls to this function in a row within the same tick / the same call stack.
660 * @param {string} cssText CSS text to be added in a `<style>` tag.
661 * @param {Function} callback Called after the insertion has occurred
663 function addEmbeddedCSS( cssText
, callback
) {
664 // Create a buffer if:
665 // - We don't have one yet.
666 // - The previous one is closed.
667 // - The next CSS chunk syntactically needs to be at the start of a stylesheet (T37562).
668 if ( !nextCssBuffer
|| nextCssBuffer
.active
=== false || cssText
.slice( 0, '@import'.length
) === '@import' ) {
676 // Linebreak for somewhat distinguishable sections
677 nextCssBuffer
.cssText
+= '\n' + cssText
;
678 nextCssBuffer
.callbacks
.push( callback
);
680 if ( nextCssBuffer
.active
=== null ) {
681 nextCssBuffer
.active
= true;
682 // The flushCssBuffer callback has its parameter bound by reference, which means
683 // 1) We can still extend the buffer from our object reference after this point.
684 // 2) We can safely re-assign the variable (not the object) to start a new buffer.
685 rAF( flushCssBuffer
.bind( null, nextCssBuffer
) );
691 * @param {string[]} modules List of module names
692 * @return {string} Hash of concatenated version hashes.
694 function getCombinedVersion( modules
) {
695 var hashes
= modules
.reduce( function ( result
, module
) {
696 return result
+ registry
[ module
].version
;
698 return fnv132( hashes
);
702 * Determine whether all dependencies are in state 'ready', which means we may
703 * execute the module or job now.
706 * @param {string[]} modules Names of modules to be checked
707 * @return {boolean} True if all modules are in state 'ready', false otherwise
709 function allReady( modules
) {
711 for ( ; i
< modules
.length
; i
++ ) {
712 if ( mw
.loader
.getState( modules
[ i
] ) !== 'ready' ) {
720 * Determine whether all direct and base dependencies are in state 'ready'
723 * @param {string} module Name of the module to be checked
724 * @return {boolean} True if all direct/base dependencies are in state 'ready'; false otherwise
726 function allWithImplicitReady( module
) {
727 return allReady( registry
[ module
].dependencies
) &&
728 ( baseModules
.indexOf( module
) !== -1 || allReady( baseModules
) );
732 * Determine whether all dependencies are in state 'ready', which means we may
733 * execute the module or job now.
736 * @param {Array} modules Names of modules to be checked
737 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
739 function anyFailed( modules
) {
742 for ( ; i
< modules
.length
; i
++ ) {
743 state
= mw
.loader
.getState( modules
[ i
] );
744 if ( state
=== 'error' || state
=== 'missing' ) {
752 * Handle propagation of module state changes and reactions to them.
754 * - When a module reaches a failure state, this should be propagated to
755 * modules that depend on the failed module.
756 * - When a module reaches a final state, pending job callbacks for the
757 * module from mw.loader.using() should be called.
758 * - When a module reaches the 'ready' state from #execute(), consider
759 * executing dependant modules now having their dependencies satisfied.
760 * - When a module reaches the 'loaded' state from mw.loader.implement,
761 * consider executing it, if it has no unsatisfied dependencies.
765 function doPropagation() {
766 var errorModule
, baseModuleError
, module
, i
, failed
, job
,
769 // Keep going until the last iteration performed no actions.
771 didPropagate
= false;
773 // Stage 1: Propagate failures
774 while ( errorModules
.length
) {
775 errorModule
= errorModules
.shift();
776 baseModuleError
= baseModules
.indexOf( errorModule
) !== -1;
777 for ( module
in registry
) {
778 if ( registry
[ module
].state
!== 'error' && registry
[ module
].state
!== 'missing' ) {
779 if ( baseModuleError
&& baseModules
.indexOf( module
) === -1 ) {
780 // Propate error from base module to all regular (non-base) modules
781 registry
[ module
].state
= 'error';
783 } else if ( registry
[ module
].dependencies
.indexOf( errorModule
) !== -1 ) {
784 // Propagate error from dependency to depending module
785 registry
[ module
].state
= 'error';
786 // .. and propagate it further
787 errorModules
.push( module
);
794 // Stage 2: Execute 'loaded' modules with no unsatisfied dependencies
795 for ( module
in registry
) {
796 if ( registry
[ module
].state
=== 'loaded' && allWithImplicitReady( module
) ) {
797 // Recursively execute all dependent modules that were already loaded
798 // (waiting for execution) and no longer have unsatisfied dependencies.
799 // Base modules may have dependencies amongst eachother to ensure correct
800 // execution order. Regular modules wait for all base modules.
801 // eslint-disable-next-line no-use-before-define
807 // Stage 3: Invoke job callbacks that are no longer blocked
808 for ( i
= 0; i
< jobs
.length
; i
++ ) {
810 failed
= anyFailed( job
.dependencies
);
811 if ( failed
|| allReady( job
.dependencies
) ) {
815 if ( failed
&& job
.error
) {
816 job
.error( new Error( 'Failed dependencies' ), job
.dependencies
);
817 } else if ( !failed
&& job
.ready
) {
821 // A user-defined callback raised an exception.
822 // Swallow it to protect our state machine!
823 mw
.trackError( 'resourceloader.exception', {
825 source
: 'load-callback'
831 } while ( didPropagate
);
833 willPropagate
= false;
837 * Request a (debounced) call to doPropagation().
841 function requestPropagation() {
842 if ( willPropagate
) {
843 // Already scheduled, or, we're already in a doPropagation stack.
846 willPropagate
= true;
847 // Yield for two reasons:
848 // * Allow successive calls to mw.loader.implement() from the same
849 // load.php response, or from the same asyncEval() to be in the
850 // propagation batch.
851 // * Allow the browser to breathe between the reception of
852 // module source code and the execution of it.
854 // Use a high priority because the user may be waiting for interactions
855 // to start being possible. But, first provide a moment (up to 'timeout')
856 // for native input event handling (e.g. scrolling/typing/clicking).
857 mw
.requestIdleCallback( doPropagation
, { timeout
: 1 } );
861 * Update a module's state in the registry and make sure any neccesary
862 * propagation will occur. See #doPropagation for more about propagation.
863 * See #registry for more about how states are used.
866 * @param {string} module
867 * @param {string} state
869 function setAndPropagate( module
, state
) {
870 registry
[ module
].state
= state
;
871 if ( state
=== 'loaded' || state
=== 'ready' || state
=== 'error' || state
=== 'missing' ) {
872 if ( state
=== 'ready' ) {
873 // Queue to later be synced to the local module store.
874 mw
.loader
.store
.add( module
);
875 } else if ( state
=== 'error' || state
=== 'missing' ) {
876 errorModules
.push( module
);
878 requestPropagation();
883 * Resolve dependencies and detect circular references.
886 * @param {string} module Name of the top-level module whose dependencies shall be
887 * resolved and sorted.
888 * @param {Array} resolved Returns a topological sort of the given module and its
889 * dependencies, such that later modules depend on earlier modules. The array
890 * contains the module names. If the array contains already some module names,
891 * this function appends its result to the pre-existing array.
892 * @param {StringSet} [unresolved] Used to detect loops in the dependency graph.
893 * @throws {Error} If an unknown module or a circular dependency is encountered
895 function sortDependencies( module
, resolved
, unresolved
) {
898 if ( !( module
in registry
) ) {
899 throw new Error( 'Unknown module: ' + module
);
902 if ( typeof registry
[ module
].skip
=== 'string' ) {
903 // eslint-disable-next-line no-new-func
904 skip
= ( new Function( registry
[ module
].skip
)() );
905 registry
[ module
].skip
= !!skip
;
907 registry
[ module
].dependencies
= [];
908 setAndPropagate( module
, 'ready' );
913 // Create unresolved if not passed in
915 unresolved
= new StringSet();
918 // Track down dependencies
919 deps
= registry
[ module
].dependencies
;
920 unresolved
.add( module
);
921 for ( i
= 0; i
< deps
.length
; i
++ ) {
922 if ( resolved
.indexOf( deps
[ i
] ) === -1 ) {
923 if ( unresolved
.has( deps
[ i
] ) ) {
925 'Circular reference detected: ' + module
+ ' -> ' + deps
[ i
]
929 sortDependencies( deps
[ i
], resolved
, unresolved
);
933 resolved
.push( module
);
937 * Get names of module that a module depends on, in their proper dependency order.
940 * @param {string[]} modules Array of string module names
941 * @return {Array} List of dependencies, including 'module'.
942 * @throws {Error} If an unregistered module or a dependency loop is encountered
944 function resolve( modules
) {
945 // Always load base modules
946 var resolved
= baseModules
.slice(),
948 for ( ; i
< modules
.length
; i
++ ) {
949 sortDependencies( modules
[ i
], resolved
);
955 * Like #resolve(), except it will silently ignore modules that
956 * are missing or have missing dependencies.
959 * @param {string[]} modules Array of string module names
960 * @return {Array} List of dependencies.
962 function resolveStubbornly( modules
) {
964 // Always load base modules
965 resolved
= baseModules
.slice(),
967 for ( ; i
< modules
.length
; i
++ ) {
968 saved
= resolved
.slice();
970 sortDependencies( modules
[ i
], resolved
);
972 // This module is not currently known, or has invalid dependencies.
973 // Most likely due to a cached reference after the module was
974 // removed, otherwise made redundant, or omitted from the registry
975 // by the ResourceLoader "target" system.
977 mw
.log
.warn( 'Skipped unresolvable module ' + modules
[ i
] );
978 if ( modules
[ i
] in registry
) {
979 // If the module was known but had unknown or circular dependencies,
980 // also track it as an error.
981 mw
.trackError( 'resourceloader.exception', {
992 * Resolve a relative file path.
994 * For example, resolveRelativePath( '../foo.js', 'resources/src/bar/bar.js' )
995 * returns 'resources/src/foo.js'.
997 * @param {string} relativePath Relative file path, starting with ./ or ../
998 * @param {string} basePath Path of the file (not directory) relativePath is relative to
999 * @return {string|null} Resolved path, or null if relativePath does not start with ./ or ../
1001 function resolveRelativePath( relativePath
, basePath
) {
1002 var prefixes
, prefix
, baseDirParts
,
1003 relParts
= relativePath
.match( /^((?:\.\.?\/)+)(.*)$/ );
1009 baseDirParts
= basePath
.split( '/' );
1010 // basePath looks like 'foo/bar/baz.js', so baseDirParts looks like [ 'foo', 'bar, 'baz.js' ]
1011 // Remove the file component at the end, so that we are left with only the directory path
1014 prefixes
= relParts
[ 1 ].split( '/' );
1015 // relParts[ 1 ] looks like '../../', so prefixes looks like [ '..', '..', '' ]
1016 // Remove the empty element at the end
1019 // For every ../ in the path prefix, remove one directory level from baseDirParts
1020 while ( ( prefix
= prefixes
.pop() ) !== undefined ) {
1021 if ( prefix
=== '..' ) {
1026 // If there's anything left of the base path, prepend it to the file path
1027 return ( baseDirParts
.length
? baseDirParts
.join( '/' ) + '/' : '' ) + relParts
[ 2 ];
1031 * Make a require() function scoped to a package file
1033 * @param {Object} moduleObj Module object from the registry
1034 * @param {string} basePath Path of the file this is scoped to. Used for relative paths.
1035 * @return {Function}
1037 function makeRequireFunction( moduleObj
, basePath
) {
1038 return function require( moduleName
) {
1039 var fileName
, fileContent
, result
, moduleParam
,
1040 scriptFiles
= moduleObj
.script
.files
;
1041 fileName
= resolveRelativePath( moduleName
, basePath
);
1042 if ( fileName
=== null ) {
1043 // Not a relative path, so it's a module name
1044 return mw
.loader
.require( moduleName
);
1047 if ( !hasOwn
.call( scriptFiles
, fileName
) ) {
1048 throw new Error( 'Cannot require undefined file ' + fileName
);
1050 if ( hasOwn
.call( moduleObj
.packageExports
, fileName
) ) {
1051 // File has already been executed, return the cached result
1052 return moduleObj
.packageExports
[ fileName
];
1055 fileContent
= scriptFiles
[ fileName
];
1056 if ( typeof fileContent
=== 'function' ) {
1057 moduleParam
= { exports
: {} };
1058 fileContent( makeRequireFunction( moduleObj
, fileName
), moduleParam
);
1059 result
= moduleParam
.exports
;
1061 // fileContent is raw data, just pass it through
1062 result
= fileContent
;
1064 moduleObj
.packageExports
[ fileName
] = result
;
1070 * Load and execute a script.
1073 * @param {string} src URL to script, will be used as the src attribute in the script tag
1074 * @param {Function} [callback] Callback to run after request resolution
1076 function addScript( src
, callback
) {
1077 // Use a <script> element rather than XHR. Using XHR changes the request
1078 // headers (potentially missing a cache hit), and reduces caching in general
1079 // since browsers cache XHR much less (if at all). And XHR means we retrieve
1080 // text, so we'd need to eval, which then messes up line numbers.
1081 // The drawback is that <script> does not offer progress events, feedback is
1082 // only given after downloading, parsing, and execution have completed.
1083 var script
= document
.createElement( 'script' );
1085 script
.onload
= script
.onerror = function () {
1086 if ( script
.parentNode
) {
1087 script
.parentNode
.removeChild( script
);
1094 document
.head
.appendChild( script
);
1098 * Queue the loading and execution of a script for a particular module.
1100 * This does for debug mode what runScript() does for production.
1103 * @param {string} src URL of the script
1104 * @param {string} moduleName Name of currently executing module
1105 * @param {Function} callback Callback to run after addScript() resolution
1107 function queueModuleScript( src
, moduleName
, callback
) {
1108 pendingRequests
.push( function () {
1109 // Keep in sync with execute()/runScript().
1110 if ( moduleName
!== 'jquery' ) {
1111 window
.require
= mw
.loader
.require
;
1112 window
.module
= registry
[ moduleName
].module
;
1114 addScript( src
, function () {
1115 // 'module.exports' should not persist after the file is executed to
1116 // avoid leakage to unrelated code. 'require' should be kept, however,
1117 // as asynchronous access to 'require' is allowed and expected. (T144879)
1118 delete window
.module
;
1120 // Start the next one (if any)
1121 if ( pendingRequests
[ 0 ] ) {
1122 pendingRequests
.shift()();
1124 handlingPendingRequests
= false;
1128 if ( !handlingPendingRequests
&& pendingRequests
[ 0 ] ) {
1129 handlingPendingRequests
= true;
1130 pendingRequests
.shift()();
1135 * Utility function for execute()
1138 * @param {string} url URL
1139 * @param {string} [media] Media attribute
1140 * @param {Node|null} [nextNode]
1142 function addLink( url
, media
, nextNode
) {
1143 var el
= document
.createElement( 'link' );
1145 el
.rel
= 'stylesheet';
1146 if ( media
&& media
!== 'all' ) {
1149 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1150 // see #addEmbeddedCSS, T33676, T43331, and T49277 for details.
1153 if ( nextNode
&& nextNode
.parentNode
) {
1154 nextNode
.parentNode
.insertBefore( el
, nextNode
);
1156 document
.head
.appendChild( el
);
1162 * @param {string} code JavaScript code
1164 function domEval( code
) {
1165 var script
= document
.createElement( 'script' );
1166 if ( mw
.config
.get( 'wgCSPNonce' ) !== false ) {
1167 script
.nonce
= mw
.config
.get( 'wgCSPNonce' );
1170 document
.head
.appendChild( script
);
1171 script
.parentNode
.removeChild( script
);
1175 * Add one or more modules to the module load queue.
1180 * @param {string[]} dependencies Array of module names in the registry
1181 * @param {Function} [ready] Callback to execute when all dependencies are ready
1182 * @param {Function} [error] Callback to execute when any dependency fails
1184 function enqueue( dependencies
, ready
, error
) {
1185 if ( allReady( dependencies
) ) {
1186 // Run ready immediately
1187 if ( ready
!== undefined ) {
1193 if ( anyFailed( dependencies
) ) {
1194 if ( error
!== undefined ) {
1195 // Execute error immediately if any dependencies have errors
1197 new Error( 'One or more dependencies failed to load' ),
1204 // Not all dependencies are ready, add to the load queue...
1206 // Add ready and error callbacks if they were given
1207 if ( ready
!== undefined || error
!== undefined ) {
1209 // Narrow down the list to modules that are worth waiting for
1210 dependencies
: dependencies
.filter( function ( module
) {
1211 var state
= registry
[ module
].state
;
1212 return state
=== 'registered' || state
=== 'loaded' || state
=== 'loading' || state
=== 'executing';
1219 dependencies
.forEach( function ( module
) {
1220 // Only queue modules that are still in the initial 'registered' state
1221 // (e.g. not ones already loading or loaded etc.).
1222 if ( registry
[ module
].state
=== 'registered' && queue
.indexOf( module
) === -1 ) {
1223 queue
.push( module
);
1231 * Executes a loaded module, making it ready to use
1234 * @param {string} module Module name to execute
1236 function execute( module
) {
1237 var key
, value
, media
, i
, urls
, cssHandle
, siteDeps
, siteDepErr
, runScript
,
1240 if ( registry
[ module
].state
!== 'loaded' ) {
1241 throw new Error( 'Module in state "' + registry
[ module
].state
+ '" may not execute: ' + module
);
1244 registry
[ module
].state
= 'executing';
1245 $CODE
.profileExecuteStart();
1247 runScript = function () {
1248 var script
, markModuleReady
, nestedAddScript
, mainScript
;
1250 $CODE
.profileScriptStart();
1251 script
= registry
[ module
].script
;
1252 markModuleReady = function () {
1253 $CODE
.profileScriptEnd();
1254 setAndPropagate( module
, 'ready' );
1256 nestedAddScript = function ( arr
, callback
, i
) {
1257 // Recursively call queueModuleScript() in its own callback
1258 // for each element of arr.
1259 if ( i
>= arr
.length
) {
1260 // We're at the end of the array
1265 queueModuleScript( arr
[ i
], module
, function () {
1266 nestedAddScript( arr
, callback
, i
+ 1 );
1271 if ( Array
.isArray( script
) ) {
1272 nestedAddScript( script
, markModuleReady
, 0 );
1274 typeof script
=== 'function' || (
1275 typeof script
=== 'object' &&
1279 if ( typeof script
=== 'function' ) {
1280 // Keep in sync with queueModuleScript() for debug mode
1281 if ( module
=== 'jquery' ) {
1282 // This is a special case for when 'jquery' itself is being loaded.
1283 // - The standard jquery.js distribution does not set `window.jQuery`
1284 // in CommonJS-compatible environments (Node.js, AMD, RequireJS, etc.).
1285 // - MediaWiki's 'jquery' module also bundles jquery.migrate.js, which
1286 // in a CommonJS-compatible environment, will use require('jquery'),
1287 // but that can't work when we're still inside that module.
1290 // Pass jQuery twice so that the signature of the closure which wraps
1291 // the script can bind both '$' and 'jQuery'.
1292 script( window
.$, window
.$, mw
.loader
.require
, registry
[ module
].module
);
1295 mainScript
= script
.files
[ script
.main
];
1296 if ( typeof mainScript
!== 'function' ) {
1297 throw new Error( 'Main file in module ' + module
+ ' must be a function' );
1299 // jQuery parameters are not passed for multi-file modules
1301 makeRequireFunction( registry
[ module
], script
.main
),
1302 registry
[ module
].module
1306 } else if ( typeof script
=== 'string' ) {
1307 // Site and user modules are legacy scripts that run in the global scope.
1308 // This is transported as a string instead of a function to avoid needing
1309 // to use string manipulation to undo the function wrapper.
1314 // Module without script
1318 // Use mw.track instead of mw.log because these errors are common in production mode
1319 // (e.g. undefined variable), and mw.log is only enabled in debug mode.
1320 setAndPropagate( module
, 'error' );
1321 $CODE
.profileScriptEnd();
1322 mw
.trackError( 'resourceloader.exception', {
1325 source
: 'module-execute'
1330 // Add localizations to message system
1331 if ( registry
[ module
].messages
) {
1332 mw
.messages
.set( registry
[ module
].messages
);
1335 // Initialise templates
1336 if ( registry
[ module
].templates
) {
1337 mw
.templates
.set( module
, registry
[ module
].templates
);
1340 // Adding of stylesheets is asynchronous via addEmbeddedCSS().
1341 // The below function uses a counting semaphore to make sure we don't call
1342 // runScript() until after this module's stylesheets have been inserted
1344 cssHandle = function () {
1345 // Increase semaphore, when creating a callback for addEmbeddedCSS.
1347 return function () {
1349 // Decrease semaphore, when said callback is invoked.
1351 if ( cssPending
=== 0 ) {
1353 // This callback is exposed to addEmbeddedCSS, which is outside the execute()
1354 // function and is not concerned with state-machine integrity. In turn,
1355 // addEmbeddedCSS() actually exposes stuff further into the browser (rAF).
1356 // If increment and decrement callbacks happen in the wrong order, or start
1357 // again afterwards, then this branch could be reached multiple times.
1358 // To protect the integrity of the state-machine, prevent that from happening
1359 // by making runScript() cannot be called more than once. We store a private
1360 // reference when we first reach this branch, then deference the original, and
1361 // call our reference to it.
1362 runScriptCopy
= runScript
;
1363 runScript
= undefined;
1369 // Process styles (see also mw.loader.implement)
1370 // * back-compat: { <media>: css }
1371 // * back-compat: { <media>: [url, ..] }
1372 // * { "css": [css, ..] }
1373 // * { "url": { <media>: [url, ..] } }
1374 if ( registry
[ module
].style
) {
1375 for ( key
in registry
[ module
].style
) {
1376 value
= registry
[ module
].style
[ key
];
1379 if ( key
!== 'url' && key
!== 'css' ) {
1380 // Backwards compatibility, key is a media-type
1381 if ( typeof value
=== 'string' ) {
1382 // back-compat: { <media>: css }
1383 // Ignore 'media' because it isn't supported (nor was it used).
1384 // Strings are pre-wrapped in "@media". The media-type was just ""
1385 // (because it had to be set to something).
1386 // This is one of the reasons why this format is no longer used.
1387 addEmbeddedCSS( value
, cssHandle() );
1389 // back-compat: { <media>: [url, ..] }
1395 // Array of css strings in key 'css',
1396 // or back-compat array of urls from media-type
1397 if ( Array
.isArray( value
) ) {
1398 for ( i
= 0; i
< value
.length
; i
++ ) {
1399 if ( key
=== 'bc-url' ) {
1400 // back-compat: { <media>: [url, ..] }
1401 addLink( value
[ i
], media
, marker
);
1402 } else if ( key
=== 'css' ) {
1403 // { "css": [css, ..] }
1404 addEmbeddedCSS( value
[ i
], cssHandle() );
1407 // Not an array, but a regular object
1408 // Array of urls inside media-type key
1409 } else if ( typeof value
=== 'object' ) {
1410 // { "url": { <media>: [url, ..] } }
1411 for ( media
in value
) {
1412 urls
= value
[ media
];
1413 for ( i
= 0; i
< urls
.length
; i
++ ) {
1414 addLink( urls
[ i
], media
, marker
);
1421 // End profiling of execute()-self before we call runScript(),
1422 // which we want to measure separately without overlap.
1423 $CODE
.profileExecuteEnd();
1425 if ( module
=== 'user' ) {
1426 // Implicit dependency on the site module. Not a real dependency because it should
1427 // run after 'site' regardless of whether it succeeds or fails.
1428 // Note: This is a simplified version of mw.loader.using(), inlined here because
1429 // mw.loader.using() is part of mediawiki.base (depends on jQuery; T192623).
1431 siteDeps
= resolve( [ 'site' ] );
1436 if ( siteDepErr
=== undefined ) {
1437 enqueue( siteDeps
, runScript
, runScript
);
1439 } else if ( cssPending
=== 0 ) {
1440 // Regular module without styles
1443 // else: runScript will get called via cssHandle()
1446 function sortQuery( o
) {
1455 for ( key
= 0; key
< a
.length
; key
++ ) {
1456 sorted
[ a
[ key
] ] = o
[ a
[ key
] ];
1462 * Converts a module map of the form `{ foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }`
1463 * to a query string of the form `foo.bar,baz|bar.baz,quux`.
1465 * See `ResourceLoader::makePackedModulesString()` in PHP, of which this is a port.
1466 * On the server, unpacking is done by `ResourceLoader::expandModuleNames()`.
1468 * Note: This is only half of the logic, the other half has to be in #batchRequest(),
1469 * because its implementation needs to keep track of potential string size in order
1470 * to decide when to split the requests due to url size.
1473 * @param {Object} moduleMap Module map
1475 * @return {string} return.str Module query string
1476 * @return {Array} return.list List of module names in matching order
1478 function buildModulesString( moduleMap
) {
1483 function restore( suffix
) {
1487 for ( prefix
in moduleMap
) {
1488 p
= prefix
=== '' ? '' : prefix
+ '.';
1489 str
.push( p
+ moduleMap
[ prefix
].join( ',' ) );
1490 list
.push
.apply( list
, moduleMap
[ prefix
].map( restore
) );
1493 str
: str
.join( '|' ),
1499 * Resolve indexed dependencies.
1501 * ResourceLoader uses an optimisation to save space which replaces module names in
1502 * dependency lists with the index of that module within the array of module
1503 * registration data if it exists. The benefit is a significant reduction in the data
1504 * size of the startup module. This function changes those dependency lists back to
1505 * arrays of strings.
1508 * @param {Array} modules Modules array
1510 function resolveIndexedDependencies( modules
) {
1512 function resolveIndex( dep
) {
1513 return typeof dep
=== 'number' ? modules
[ dep
][ 0 ] : dep
;
1515 for ( i
= 0; i
< modules
.length
; i
++ ) {
1516 deps
= modules
[ i
][ 2 ];
1518 for ( j
= 0; j
< deps
.length
; j
++ ) {
1519 deps
[ j
] = resolveIndex( deps
[ j
] );
1527 * @param {Object} params Map of parameter names to values
1530 function makeQueryString( params
) {
1531 return Object
.keys( params
).map( function ( key
) {
1532 return encodeURIComponent( key
) + '=' + encodeURIComponent( params
[ key
] );
1537 * Create network requests for a batch of modules.
1539 * This is an internal method for #work(). This must not be called directly
1540 * unless the modules are already registered, and no request is in progress,
1541 * and the module state has already been set to `loading`.
1544 * @param {string[]} batch
1546 function batchRequest( batch
) {
1547 var reqBase
, splits
, b
, bSource
, bGroup
,
1548 source
, group
, i
, modules
, sourceLoadScript
,
1549 currReqBase
, currReqBaseLength
, moduleMap
, currReqModules
, l
,
1550 lastDotIndex
, prefix
, suffix
, bytesAdded
;
1553 * Start the currently drafted request to the server.
1557 function doRequest() {
1558 // Optimisation: Inherit (Object.create), not copy ($.extend)
1559 var query
= Object
.create( currReqBase
),
1560 packed
= buildModulesString( moduleMap
);
1561 query
.modules
= packed
.str
;
1562 // The packing logic can change the effective order, even if the input was
1563 // sorted. As such, the call to getCombinedVersion() must use this
1564 // effective order, instead of currReqModules, as otherwise the combined
1565 // version will not match the hash expected by the server based on
1566 // combining versions from the module query string in-order. (T188076)
1567 query
.version
= getCombinedVersion( packed
.list
);
1568 query
= sortQuery( query
);
1569 addScript( sourceLoadScript
+ '?' + makeQueryString( query
) );
1572 if ( !batch
.length
) {
1576 // Always order modules alphabetically to help reduce cache
1577 // misses for otherwise identical content.
1580 // Query parameters common to all requests
1581 reqBase
= $VARS
.reqBase
;
1583 // Split module list by source and by group.
1584 splits
= Object
.create( null );
1585 for ( b
= 0; b
< batch
.length
; b
++ ) {
1586 bSource
= registry
[ batch
[ b
] ].source
;
1587 bGroup
= registry
[ batch
[ b
] ].group
;
1588 if ( !splits
[ bSource
] ) {
1589 splits
[ bSource
] = Object
.create( null );
1591 if ( !splits
[ bSource
][ bGroup
] ) {
1592 splits
[ bSource
][ bGroup
] = [];
1594 splits
[ bSource
][ bGroup
].push( batch
[ b
] );
1597 for ( source
in splits
) {
1598 sourceLoadScript
= sources
[ source
];
1600 for ( group
in splits
[ source
] ) {
1602 // Cache access to currently selected list of
1603 // modules for this group from this source.
1604 modules
= splits
[ source
][ group
];
1606 // Query parameters common to requests for this module group
1607 // Optimisation: Inherit (Object.create), not copy ($.extend)
1608 currReqBase
= Object
.create( reqBase
);
1609 // User modules require a user name in the query string.
1610 if ( group
=== $VARS
.groupUser
&& mw
.config
.get( 'wgUserName' ) !== null ) {
1611 currReqBase
.user
= mw
.config
.get( 'wgUserName' );
1614 // In addition to currReqBase, doRequest() will also add 'modules' and 'version'.
1615 // > '&modules='.length === 9
1616 // > '&version=12345'.length === 14
1618 currReqBaseLength
= makeQueryString( currReqBase
).length
+ 23;
1620 // We may need to split up the request to honor the query string length limit,
1621 // so build it piece by piece.
1622 l
= currReqBaseLength
;
1623 moduleMap
= Object
.create( null ); // { prefix: [ suffixes ] }
1624 currReqModules
= [];
1626 for ( i
= 0; i
< modules
.length
; i
++ ) {
1627 // Determine how many bytes this module would add to the query string
1628 lastDotIndex
= modules
[ i
].lastIndexOf( '.' );
1629 // If lastDotIndex is -1, substr() returns an empty string
1630 prefix
= modules
[ i
].substr( 0, lastDotIndex
);
1631 suffix
= modules
[ i
].slice( lastDotIndex
+ 1 );
1632 bytesAdded
= moduleMap
[ prefix
] ?
1633 suffix
.length
+ 3 : // '%2C'.length == 3
1634 modules
[ i
].length
+ 3; // '%7C'.length == 3
1636 // If the url would become too long, create a new one, but don't create empty requests
1637 if ( currReqModules
.length
&& l
+ bytesAdded
> mw
.loader
.maxQueryLength
) {
1638 // Dispatch what we've got...
1640 // .. and start again.
1641 l
= currReqBaseLength
;
1642 moduleMap
= Object
.create( null );
1643 currReqModules
= [];
1645 mw
.track( 'resourceloader.splitRequest', { maxQueryLength
: mw
.loader
.maxQueryLength
} );
1647 if ( !moduleMap
[ prefix
] ) {
1648 moduleMap
[ prefix
] = [];
1651 moduleMap
[ prefix
].push( suffix
);
1652 currReqModules
.push( modules
[ i
] );
1654 // If there's anything left in moduleMap, request that too
1655 if ( currReqModules
.length
) {
1664 * @param {string[]} implementations Array containing pieces of JavaScript code in the
1665 * form of calls to mw.loader#implement().
1666 * @param {Function} cb Callback in case of failure
1667 * @param {Error} cb.err
1669 function asyncEval( implementations
, cb
) {
1670 if ( !implementations
.length
) {
1673 mw
.requestIdleCallback( function () {
1675 domEval( implementations
.join( ';' ) );
1683 * Make a versioned key for a specific module.
1686 * @param {string} module Module name
1687 * @return {string|null} Module key in format '`[name]@[version]`',
1688 * or null if the module does not exist
1690 function getModuleKey( module
) {
1691 return module
in registry
? ( module
+ '@' + registry
[ module
].version
) : null;
1696 * @param {string} key Module name or '`[name]@[version]`'
1699 function splitModuleKey( key
) {
1700 var index
= key
.indexOf( '@' );
1701 if ( index
=== -1 ) {
1708 name
: key
.slice( 0, index
),
1709 version
: key
.slice( index
+ 1 )
1715 * @param {string} module
1716 * @param {string|number} [version]
1717 * @param {string[]} [dependencies]
1718 * @param {string} [group]
1719 * @param {string} [source]
1720 * @param {string} [skip]
1722 function registerOne( module
, version
, dependencies
, group
, source
, skip
) {
1723 if ( module
in registry
) {
1724 throw new Error( 'module already registered: ' + module
);
1726 registry
[ module
] = {
1727 // Exposed to execute() for mw.loader.implement() closures.
1728 // Import happens via require().
1732 // module.export objects for each package file inside this module
1734 version
: String( version
|| '' ),
1735 dependencies
: dependencies
|| [],
1736 group
: typeof group
=== 'undefined' ? null : group
,
1737 source
: typeof source
=== 'string' ? source
: 'local',
1738 state
: 'registered',
1739 skip
: typeof skip
=== 'string' ? skip
: null
1743 /* Public Members */
1746 * The module registry is exposed as an aid for debugging and inspecting page
1747 * state; it is not a public interface for modifying the registry.
1753 moduleRegistry
: registry
,
1756 * Exposed for testing and debugging only.
1758 * @see #batchRequest
1762 maxQueryLength
: $VARS
.maxQueryLength
,
1765 * @inheritdoc #newStyleTag
1768 addStyleTag
: newStyleTag
,
1775 * Start loading of all queued module dependencies.
1780 var implementations
, sourceModules
,
1784 // Appends a list of modules from the queue to the batch
1785 for ( ; q
< queue
.length
; q
++ ) {
1786 // Only load modules which are registered
1787 if ( queue
[ q
] in registry
&& registry
[ queue
[ q
] ].state
=== 'registered' ) {
1788 // Prevent duplicate entries
1789 if ( batch
.indexOf( queue
[ q
] ) === -1 ) {
1790 batch
.push( queue
[ q
] );
1791 // Mark registered modules as loading
1792 registry
[ queue
[ q
] ].state
= 'loading';
1797 // Now that the queue has been processed into a batch, clear the queue.
1798 // This MUST happen before we initiate any eval or network request. Otherwise,
1799 // it is possible for a cached script to instantly trigger the same work queue
1800 // again; all before we've cleared it causing each request to include modules
1801 // which are already loaded.
1804 if ( !batch
.length
) {
1808 mw
.loader
.store
.init();
1809 if ( mw
.loader
.store
.enabled
) {
1810 implementations
= [];
1812 batch
= batch
.filter( function ( module
) {
1813 var implementation
= mw
.loader
.store
.get( module
);
1814 if ( implementation
) {
1815 implementations
.push( implementation
);
1816 sourceModules
.push( module
);
1821 asyncEval( implementations
, function ( err
) {
1823 // Not good, the cached mw.loader.implement calls failed! This should
1824 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1825 // Depending on how corrupt the string is, it is likely that some
1826 // modules' implement() succeeded while the ones after the error will
1827 // never run and leave their modules in the 'loading' state forever.
1828 mw
.loader
.store
.stats
.failed
++;
1830 // Since this is an error not caused by an individual module but by
1831 // something that infected the implement call itself, don't take any
1832 // risks and clear everything in this cache.
1833 mw
.loader
.store
.clear();
1835 mw
.trackError( 'resourceloader.exception', {
1837 source
: 'store-eval'
1839 // Re-add the failed ones that are still pending back to the batch
1840 failed
= sourceModules
.filter( function ( module
) {
1841 return registry
[ module
].state
=== 'loading';
1843 batchRequest( failed
);
1847 batchRequest( batch
);
1851 * Register a source.
1853 * The #work() method will use this information to split up requests by source.
1855 * mw.loader.addSource( { mediawikiwiki: 'https://www.mediawiki.org/w/load.php' } );
1858 * @param {Object} ids An object mapping ids to load.php end point urls
1859 * @throws {Error} If source id is already registered
1861 addSource: function ( ids
) {
1864 if ( id
in sources
) {
1865 throw new Error( 'source already registered: ' + id
);
1867 sources
[ id
] = ids
[ id
];
1872 * Register a module, letting the system know about it and its properties.
1874 * The startup module calls this method.
1876 * When using multiple module registration by passing an array, dependencies that
1877 * are specified as references to modules within the array will be resolved before
1878 * the modules are registered.
1880 * @param {string|Array} modules Module name or array of arrays, each containing
1881 * a list of arguments compatible with this method
1882 * @param {string|number} [version] Module version hash (falls backs to empty string)
1883 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1884 * @param {string[]} [dependencies] Array of module names on which this module depends.
1885 * @param {string} [group=null] Group which the module is in
1886 * @param {string} [source='local'] Name of the source
1887 * @param {string} [skip=null] Script body of the skip function
1889 register: function ( modules
) {
1891 if ( typeof modules
=== 'object' ) {
1892 resolveIndexedDependencies( modules
);
1893 // Optimisation: Up to 55% faster.
1894 // Typically called only once, and with a batch.
1895 // See <https://gist.github.com/Krinkle/f06fdb3de62824c6c16f02a0e6ce0e66>
1896 // Benchmarks taught us that the code for adding an object to `registry`
1897 // should actually be inline, or in a simple function that does no
1898 // arguments manipulation, and isn't also the caller itself.
1899 // JS semantics make it hard to optimise recursion to a different
1900 // signature of itself.
1901 for ( i
= 0; i
< modules
.length
; i
++ ) {
1902 registerOne
.apply( null, modules
[ i
] );
1905 registerOne
.apply( null, arguments
);
1910 * Implement a module given the components that make up the module.
1912 * When #load() or #using() requests one or more modules, the server
1913 * response contain calls to this function.
1915 * @param {string} module Name of module and current module version. Formatted
1916 * as '`[name]@[version]`". This version should match the requested version
1917 * (from #batchRequest and #registry). This avoids race conditions (T117587).
1918 * For back-compat with MediaWiki 1.27 and earlier, the version may be omitted.
1919 * @param {Function|Array|string|Object} [script] Module code. This can be a function,
1920 * a list of URLs to load via `<script src>`, a string for `$.globalEval()`, or an
1921 * object like {"files": {"foo.js":function, "bar.js": function, ...}, "main": "foo.js"}.
1922 * If an object is provided, the main file will be executed immediately, and the other
1923 * files will only be executed if loaded via require(). If a function or string is
1924 * provided, it will be executed/evaluated immediately. If an array is provided, all
1925 * URLs in the array will be loaded immediately, and executed as soon as they arrive.
1926 * @param {Object} [style] Should follow one of the following patterns:
1928 * { "css": [css, ..] }
1929 * { "url": { <media>: [url, ..] } }
1931 * And for backwards compatibility (needs to be supported forever due to caching):
1934 * { <media>: [url, ..] }
1936 * The reason css strings are not concatenated anymore is T33676. We now check
1937 * whether it's safe to extend the stylesheet.
1940 * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1941 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1943 implement: function ( module
, script
, style
, messages
, templates
) {
1944 var split
= splitModuleKey( module
),
1946 version
= split
.version
;
1947 // Automatically register module
1948 if ( !( name
in registry
) ) {
1949 mw
.loader
.register( name
);
1951 // Check for duplicate implementation
1952 if ( registry
[ name
].script
!== undefined ) {
1953 throw new Error( 'module already implemented: ' + name
);
1956 // Without this reset, if there is a version mismatch between the
1957 // requested and received module version, then mw.loader.store would
1958 // cache the response under the requested key. Thus poisoning the cache
1959 // indefinitely with a stale value. (T117587)
1960 registry
[ name
].version
= version
;
1962 // Attach components
1963 registry
[ name
].script
= script
|| null;
1964 registry
[ name
].style
= style
|| null;
1965 registry
[ name
].messages
= messages
|| null;
1966 registry
[ name
].templates
= templates
|| null;
1967 // The module may already have been marked as erroneous
1968 if ( registry
[ name
].state
!== 'error' && registry
[ name
].state
!== 'missing' ) {
1969 setAndPropagate( name
, 'loaded' );
1974 * Load an external script or one or more modules.
1976 * This method takes a list of unrelated modules. Use cases:
1978 * - A web page will be composed of many different widgets. These widgets independently
1979 * queue their ResourceLoader modules (`OutputPage::addModules()`). If any of them
1980 * have problems, or are no longer known (e.g. cached HTML), the other modules
1981 * should still be loaded.
1982 * - This method is used for preloading, which must not throw. Later code that
1983 * calls #using() will handle the error.
1985 * @param {string|Array} modules Either the name of a module, array of modules,
1986 * or a URL of an external script or style
1987 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
1988 * external script or style; acceptable values are "text/css" and
1989 * "text/javascript"; if no type is provided, text/javascript is assumed.
1990 * @throws {Error} If type is invalid
1992 load: function ( modules
, type
) {
1993 if ( typeof modules
=== 'string' && /^(https?:)?\/?\//.test( modules
) ) {
1994 // Called with a url like so:
1995 // - "https://example.org/x.js"
1996 // - "http://example.org/x.js"
1997 // - "//example.org/x.js"
1999 if ( type
=== 'text/css' ) {
2001 } else if ( type
=== 'text/javascript' || type
=== undefined ) {
2002 addScript( modules
);
2005 throw new Error( 'Invalid type ' + type
);
2008 // One or more modules
2009 modules
= typeof modules
=== 'string' ? [ modules
] : modules
;
2010 // Resolve modules into flat list for internal queuing.
2011 // This also filters out unknown modules and modules with
2012 // unknown dependencies, allowing the rest to continue. (T36853)
2013 enqueue( resolveStubbornly( modules
), undefined, undefined );
2018 * Change the state of one or more modules.
2020 * @param {Object} states Object of module name/state pairs
2022 state: function ( states
) {
2024 for ( module
in states
) {
2025 state
= states
[ module
];
2026 if ( !( module
in registry
) ) {
2027 mw
.loader
.register( module
);
2029 setAndPropagate( module
, state
);
2034 * Get the version of a module.
2036 * @param {string} module Name of module
2037 * @return {string|null} The version, or null if the module (or its version) is not
2040 getVersion: function ( module
) {
2041 return module
in registry
? registry
[ module
].version
: null;
2045 * Get the state of a module.
2047 * @param {string} module Name of module
2048 * @return {string|null} The state, or null if the module (or its state) is not
2051 getState: function ( module
) {
2052 return module
in registry
? registry
[ module
].state
: null;
2056 * Get the names of all registered modules.
2060 getModuleNames: function () {
2061 return Object
.keys( registry
);
2065 * Get the exported value of a module.
2067 * This static method is publicly exposed for debugging purposes
2068 * only and must not be used in production code. In production code,
2069 * please use the dynamically provided `require()` function instead.
2071 * In case of lazy-loaded modules via mw.loader#using(), the returned
2072 * Promise provides the function, see #using() for examples.
2076 * @param {string} moduleName Module name
2077 * @return {Mixed} Exported value
2079 require: function ( moduleName
) {
2080 var state
= mw
.loader
.getState( moduleName
);
2082 // Only ready modules can be required
2083 if ( state
!== 'ready' ) {
2084 // Module may've forgotten to declare a dependency
2085 throw new Error( 'Module "' + moduleName
+ '" is not loaded' );
2088 return registry
[ moduleName
].module
.exports
;
2092 * On browsers that implement the localStorage API, the module store serves as a
2093 * smart complement to the browser cache. Unlike the browser cache, the module store
2094 * can slice a concatenated response from ResourceLoader into its constituent
2095 * modules and cache each of them separately, using each module's versioning scheme
2096 * to determine when the cache should be invalidated.
2100 * @class mw.loader.store
2103 // Whether the store is in use on this page.
2106 // Modules whose serialised form exceeds 100 kB won't be stored (T66721).
2107 MODULE_SIZE_MAX
: 1e5
,
2109 // The contents of the store, mapping '[name]@[version]' keys
2110 // to module implementations.
2113 // Names of modules to be stored during the next update.
2114 // See add() and update().
2118 stats
: { hits
: 0, misses
: 0, expired
: 0, failed
: 0 },
2121 * Construct a JSON-serializable object representing the content of the store.
2123 * @return {Object} Module store contents.
2125 toJSON: function () {
2127 items
: mw
.loader
.store
.items
,
2128 vary
: mw
.loader
.store
.vary
,
2129 // Store with 1e7 ms accuracy (1e4 seconds, or ~ 2.7 hours),
2130 // which is enough for the purpose of expiring after ~ 30 days.
2131 asOf
: Math
.ceil( Date
.now() / 1e7
)
2136 * The localStorage key for the entire module store. The key references
2137 * $wgDBname to prevent clashes between wikis which share a common host.
2139 * @property {string}
2141 key
: $VARS
.storeKey
,
2144 * A string containing various factors on which to the module cache should vary.
2146 * @property {string}
2148 vary
: $VARS
.storeVary
,
2151 * Initialize the store.
2153 * Retrieves store from localStorage and (if successfully retrieved) decoding
2154 * the stored JSON value to a plain object.
2156 * The try / catch block is used for JSON & localStorage feature detection.
2157 * See the in-line documentation for Modernizr's localStorage feature detection
2158 * code for a full account of why we need a try / catch:
2159 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2164 if ( this.enabled
!== null ) {
2170 !$VARS
.storeEnabled
||
2172 // Disabled because localStorage quotas are tight and (in Firefox's case)
2173 // shared by multiple origins.
2174 // See T66721, and <https://bugzilla.mozilla.org/show_bug.cgi?id=1064466>.
2175 /Firefox/.test( navigator
.userAgent
)
2177 // Clear any previous store to free up space. (T66721)
2179 this.enabled
= false;
2184 // This a string we stored, or `null` if the key does not (yet) exist.
2185 raw
= localStorage
.getItem( this.key
);
2186 // If we get here, localStorage is available; mark enabled
2187 this.enabled
= true;
2188 // If null, JSON.parse() will cast to string and re-parse, still null.
2189 data
= JSON
.parse( raw
);
2191 typeof data
.items
=== 'object' &&
2192 data
.vary
=== this.vary
&&
2193 // Only use if it's been less than 30 days since the data was written
2194 // 30 days = 2,592,000 s = 2,592,000,000 ms = ± 259e7 ms
2195 Date
.now() < ( data
.asOf
* 1e7
) + 259e7
2197 // The data is not corrupt, matches our vary context, and has not expired.
2198 this.items
= data
.items
;
2202 // Perhaps localStorage was disabled by the user, or got corrupted.
2203 // See point 3 and 4 below. (T195647)
2206 // If we get here, one of four things happened:
2208 // 1. localStorage did not contain our store key.
2209 // This means `raw` is `null`, and we're on a fresh page view (cold cache).
2210 // The store was enabled, and `items` starts fresh.
2212 // 2. localStorage contained parseable data under our store key,
2213 // but it's not applicable to our current context (see #vary).
2214 // The store was enabled, and `items` starts fresh.
2216 // 3. JSON.parse threw (localStorage contained corrupt data).
2217 // This means `raw` contains a string.
2218 // The store was enabled, and `items` starts fresh.
2220 // 4. localStorage threw (disabled or otherwise unavailable).
2221 // This means `raw` was never assigned.
2222 // We will disable the store below.
2223 if ( raw
=== undefined ) {
2224 // localStorage failed; disable store
2225 this.enabled
= false;
2230 * Retrieve a module from the store and update cache hit stats.
2232 * @param {string} module Module name
2233 * @return {string|boolean} Module implementation or false if unavailable
2235 get: function ( module
) {
2238 if ( !this.enabled
) {
2242 key
= getModuleKey( module
);
2243 if ( key
in this.items
) {
2245 return this.items
[ key
];
2248 this.stats
.misses
++;
2253 * Queue the name of a module that the next update should consider storing.
2256 * @param {string} module Module name
2258 add: function ( module
) {
2259 if ( !this.enabled
) {
2262 this.queue
.push( module
);
2263 this.requestUpdate();
2267 * Add the contents of the named module to the in-memory store.
2269 * This method does not guarantee that the module will be stored.
2270 * Inspection of the module's meta data and size will ultimately decide that.
2272 * This method is considered internal to mw.loader.store and must only
2273 * be called if the store is enabled.
2276 * @param {string} module Module name
2278 set: function ( module
) {
2281 descriptor
= mw
.loader
.moduleRegistry
[ module
];
2283 key
= getModuleKey( module
);
2286 // Already stored a copy of this exact version
2287 key
in this.items
||
2288 // Module failed to load
2290 descriptor
.state
!== 'ready' ||
2291 // Unversioned, private, or site-/user-specific
2292 !descriptor
.version
||
2293 descriptor
.group
=== $VARS
.groupPrivate
||
2294 descriptor
.group
=== $VARS
.groupUser
||
2295 // Partial descriptor
2296 // (e.g. skipped module, or style module with state=ready)
2297 [ descriptor
.script
, descriptor
.style
, descriptor
.messages
,
2298 descriptor
.templates
].indexOf( undefined ) !== -1
2305 if ( typeof descriptor
.script
=== 'function' ) {
2306 // Function literal: cast to string
2307 encodedScript
= String( descriptor
.script
);
2309 // Plain object: serialise as object literal (not JSON),
2310 // making sure to preserve the functions.
2311 typeof descriptor
.script
=== 'object' &&
2312 descriptor
.script
&&
2313 !Array
.isArray( descriptor
.script
)
2315 encodedScript
= '{' +
2316 'main:' + JSON
.stringify( descriptor
.script
.main
) + ',' +
2318 Object
.keys( descriptor
.script
.files
).map( function ( key
) {
2319 var value
= descriptor
.script
.files
[ key
];
2320 return JSON
.stringify( key
) + ':' +
2321 ( typeof value
=== 'function' ? value
: JSON
.stringify( value
) );
2325 // Array of urls, or null.
2326 encodedScript
= JSON
.stringify( descriptor
.script
);
2329 JSON
.stringify( key
),
2331 JSON
.stringify( descriptor
.style
),
2332 JSON
.stringify( descriptor
.messages
),
2333 JSON
.stringify( descriptor
.templates
)
2336 mw
.trackError( 'resourceloader.exception', {
2338 source
: 'store-localstorage-json'
2343 src
= 'mw.loader.implement(' + args
.join( ',' ) + ');';
2344 if ( src
.length
> this.MODULE_SIZE_MAX
) {
2347 this.items
[ key
] = src
;
2351 * Iterate through the module store, removing any item that does not correspond
2352 * (in name and version) to an item in the module registry.
2354 prune: function () {
2357 for ( key
in this.items
) {
2358 module
= key
.slice( 0, key
.indexOf( '@' ) );
2359 if ( getModuleKey( module
) !== key
) {
2360 this.stats
.expired
++;
2361 delete this.items
[ key
];
2362 } else if ( this.items
[ key
].length
> this.MODULE_SIZE_MAX
) {
2363 // This value predates the enforcement of a size limit on cached modules.
2364 delete this.items
[ key
];
2370 * Clear the entire module store right now.
2372 clear: function () {
2375 localStorage
.removeItem( this.key
);
2380 * Request a sync of the in-memory store back to persisted localStorage.
2382 * This function debounces updates. The debouncing logic should account
2383 * for the following factors:
2385 * - Writing to localStorage is an expensive operation that must not happen
2386 * during the critical path of initialising and executing module code.
2387 * Instead, it should happen at a later time after modules have been given
2388 * time and priority to do their thing first.
2390 * - This method is called from mw.loader.store.add(), which will be called
2391 * hundreds of times on a typical page, including within the same call-stack
2392 * and eventloop-tick. This is because responses from load.php happen in
2393 * batches. As such, we want to allow all modules from the same load.php
2394 * response to be written to disk with a single flush, not many.
2396 * - Repeatedly deleting and creating timers is non-trivial.
2398 * - localStorage is shared by all pages from the same origin, if multiple
2399 * pages are loaded with different module sets, the possibility exists that
2400 * modules saved by one page will be clobbered by another. The impact of
2401 * this is minor, it merely causes a less efficient cache use, and the
2402 * problem would be corrected by subsequent page views.
2404 * This method is considered internal to mw.loader.store and must only
2405 * be called if the store is enabled.
2410 requestUpdate
: ( function () {
2411 var hasPendingWrites
= false;
2413 function flushWrites() {
2416 // Remove anything from the in-memory store that came from previous page
2417 // loads that no longer corresponds with current module names and versions.
2418 mw
.loader
.store
.prune();
2419 // Process queued module names, serialise their contents to the in-memory store.
2420 while ( mw
.loader
.store
.queue
.length
) {
2421 mw
.loader
.store
.set( mw
.loader
.store
.queue
.shift() );
2424 key
= mw
.loader
.store
.key
;
2426 // Replacing the content of the module store might fail if the new
2427 // contents would exceed the browser's localStorage size limit. To
2428 // avoid clogging the browser with stale data, always remove the old
2429 // value before attempting to set the new one.
2430 localStorage
.removeItem( key
);
2431 data
= JSON
.stringify( mw
.loader
.store
);
2432 localStorage
.setItem( key
, data
);
2434 mw
.trackError( 'resourceloader.exception', {
2436 source
: 'store-localstorage-update'
2440 // Let the next call to requestUpdate() create a new timer.
2441 hasPendingWrites
= false;
2444 function onTimeout() {
2445 // Defer the actual write via requestIdleCallback
2446 mw
.requestIdleCallback( flushWrites
);
2449 return function () {
2450 // On the first call to requestUpdate(), create a timer that
2451 // waits at least two seconds, then calls onTimeout.
2452 // The main purpose is to allow the current batch of load.php
2453 // responses to complete before we do anything. This batch can
2454 // trigger many hundreds of calls to requestUpdate().
2455 if ( !hasPendingWrites
) {
2456 hasPendingWrites
= true;
2457 setTimeout( onTimeout
, 2000 );
2466 // Attach to window and globally alias
2467 window
.mw
= window
.mediaWiki
= mw
;