Merge "resourceloader: Remove redundant calls to getState() in mw.loader.enqueue()"
[lhc/web/wiklou.git] / resources / src / startup / mediawiki.js
1 /**
2 * Base library for MediaWiki.
3 *
4 * Exposed globally as `mediaWiki` with `mw` as shortcut.
5 *
6 * @class mw
7 * @alternateClassName mediaWiki
8 * @singleton
9 */
10 /* global $VARS, $CODE */
11
12 ( function () {
13 'use strict';
14
15 var mw, StringSet, log,
16 hasOwn = Object.prototype.hasOwnProperty,
17 trackQueue = [];
18
19 /**
20 * FNV132 hash function
21 *
22 * This function implements the 32-bit version of FNV-1.
23 * It is equivalent to hash( 'fnv132', ... ) in PHP, except
24 * its output is base 36 rather than hex.
25 * See <https://en.wikipedia.org/wiki/FNV_hash_function>
26 *
27 * @private
28 * @param {string} str String to hash
29 * @return {string} hash as an seven-character base 36 string
30 */
31 function fnv132( str ) {
32 /* eslint-disable no-bitwise */
33 var hash = 0x811C9DC5,
34 i;
35
36 for ( i = 0; i < str.length; i++ ) {
37 hash += ( hash << 1 ) + ( hash << 4 ) + ( hash << 7 ) + ( hash << 8 ) + ( hash << 24 );
38 hash ^= str.charCodeAt( i );
39 }
40
41 hash = ( hash >>> 0 ).toString( 36 );
42 while ( hash.length < 7 ) {
43 hash = '0' + hash;
44 }
45
46 return hash;
47 /* eslint-enable no-bitwise */
48 }
49
50 function defineFallbacks() {
51 // <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set>
52 StringSet = window.Set || ( function () {
53 /**
54 * @private
55 * @class
56 */
57 function StringSet() {
58 this.set = {};
59 }
60 StringSet.prototype.add = function ( value ) {
61 this.set[ value ] = true;
62 };
63 StringSet.prototype.has = function ( value ) {
64 return hasOwn.call( this.set, value );
65 };
66 return StringSet;
67 }() );
68 }
69
70 /**
71 * Alias property to the global object.
72 *
73 * @private
74 * @static
75 * @member mw.Map
76 * @param {mw.Map} map
77 * @param {string} key
78 * @param {Mixed} value
79 */
80 function setGlobalMapValue( map, key, value ) {
81 map.values[ key ] = value;
82 log.deprecate(
83 window,
84 key,
85 value,
86 // Deprecation notice for mw.config globals (T58550, T72470)
87 map === mw.config && 'Use mw.config instead.'
88 );
89 }
90
91 /**
92 * Log a message to window.console, if possible.
93 *
94 * Useful to force logging of some errors that are otherwise hard to detect (i.e., this logs
95 * also in production mode). Gets console references in each invocation instead of caching the
96 * reference, so that debugging tools loaded later are supported (e.g. Firebug Lite in IE).
97 *
98 * @private
99 * @param {string} topic Stream name passed by mw.track
100 * @param {Object} data Data passed by mw.track
101 * @param {Error} [data.exception]
102 * @param {string} data.source Error source
103 * @param {string} [data.module] Name of module which caused the error
104 */
105 function logError( topic, data ) {
106 /* eslint-disable no-console */
107 var msg,
108 e = data.exception,
109 source = data.source,
110 module = data.module,
111 console = window.console;
112
113 if ( console && console.log ) {
114 msg = ( e ? 'Exception' : 'Error' ) + ' in ' + source;
115 if ( module ) {
116 msg += ' in module ' + module;
117 }
118 msg += ( e ? ':' : '.' );
119 console.log( msg );
120
121 // If we have an exception object, log it to the warning channel to trigger
122 // proper stacktraces in browsers that support it.
123 if ( e && console.warn ) {
124 console.warn( e );
125 }
126 }
127 /* eslint-enable no-console */
128 }
129
130 /**
131 * Create an object that can be read from or written to via methods that allow
132 * interaction both with single and multiple properties at once.
133 *
134 * @private
135 * @class mw.Map
136 *
137 * @constructor
138 * @param {boolean} [global=false] Whether to synchronise =values to the global
139 * window object (for backwards-compatibility with mw.config; T72470). Values are
140 * copied in one direction only. Changes to globals do not reflect in the map.
141 */
142 function Map( global ) {
143 this.values = {};
144 if ( global === true ) {
145 // Override #set to also set the global variable
146 this.set = function ( selection, value ) {
147 var s;
148 if ( arguments.length > 1 ) {
149 if ( typeof selection !== 'string' ) {
150 return false;
151 }
152 setGlobalMapValue( this, selection, value );
153 return true;
154 }
155 if ( typeof selection === 'object' ) {
156 for ( s in selection ) {
157 setGlobalMapValue( this, s, selection[ s ] );
158 }
159 return true;
160 }
161 return false;
162 };
163 }
164 }
165
166 Map.prototype = {
167 constructor: Map,
168
169 /**
170 * Get the value of one or more keys.
171 *
172 * If called with no arguments, all values are returned.
173 *
174 * @param {string|Array} [selection] Key or array of keys to retrieve values for.
175 * @param {Mixed} [fallback=null] Value for keys that don't exist.
176 * @return {Mixed|Object|null} If selection was a string, returns the value,
177 * If selection was an array, returns an object of key/values.
178 * If no selection is passed, a new object with all key/values is returned.
179 */
180 get: function ( selection, fallback ) {
181 var results, i;
182 fallback = arguments.length > 1 ? fallback : null;
183
184 if ( Array.isArray( selection ) ) {
185 results = {};
186 for ( i = 0; i < selection.length; i++ ) {
187 if ( typeof selection[ i ] === 'string' ) {
188 results[ selection[ i ] ] = hasOwn.call( this.values, selection[ i ] ) ?
189 this.values[ selection[ i ] ] :
190 fallback;
191 }
192 }
193 return results;
194 }
195
196 if ( typeof selection === 'string' ) {
197 return hasOwn.call( this.values, selection ) ?
198 this.values[ selection ] :
199 fallback;
200 }
201
202 if ( selection === undefined ) {
203 results = {};
204 for ( i in this.values ) {
205 results[ i ] = this.values[ i ];
206 }
207 return results;
208 }
209
210 // Invalid selection key
211 return fallback;
212 },
213
214 /**
215 * Set one or more key/value pairs.
216 *
217 * @param {string|Object} selection Key to set value for, or object mapping keys to values
218 * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
219 * @return {boolean} True on success, false on failure
220 */
221 set: function ( selection, value ) {
222 var s;
223 // Use `arguments.length` because `undefined` is also a valid value.
224 if ( arguments.length > 1 ) {
225 if ( typeof selection !== 'string' ) {
226 return false;
227 }
228 this.values[ selection ] = value;
229 return true;
230 }
231 if ( typeof selection === 'object' ) {
232 for ( s in selection ) {
233 this.values[ s ] = selection[ s ];
234 }
235 return true;
236 }
237 return false;
238 },
239
240 /**
241 * Check if one or more keys exist.
242 *
243 * @param {Mixed} selection Key or array of keys to check
244 * @return {boolean} True if the key(s) exist
245 */
246 exists: function ( selection ) {
247 var i;
248 if ( Array.isArray( selection ) ) {
249 for ( i = 0; i < selection.length; i++ ) {
250 if ( typeof selection[ i ] !== 'string' || !hasOwn.call( this.values, selection[ i ] ) ) {
251 return false;
252 }
253 }
254 return true;
255 }
256 return typeof selection === 'string' && hasOwn.call( this.values, selection );
257 }
258 };
259
260 defineFallbacks();
261
262 /* eslint-disable no-console */
263 log = ( function () {
264 /**
265 * Write a verbose message to the browser's console in debug mode.
266 *
267 * This method is mainly intended for verbose logging. It is a no-op in production mode.
268 * In ResourceLoader debug mode, it will use the browser's console if available, with
269 * fallback to creating a console interface in the DOM and logging messages there.
270 *
271 * See {@link mw.log} for other logging methods.
272 *
273 * @member mw
274 * @param {...string} msg Messages to output to console.
275 */
276 var log = function () {},
277 console = window.console;
278
279 // Note: Keep list of methods in sync with restoration in mediawiki.log.js
280 // when adding or removing mw.log methods below!
281
282 /**
283 * Collection of methods to help log messages to the console.
284 *
285 * @class mw.log
286 * @singleton
287 */
288
289 /**
290 * Write a message to the browser console's warning channel.
291 *
292 * This method is a no-op in browsers that don't implement the Console API.
293 *
294 * @param {...string} msg Messages to output to console
295 */
296 log.warn = console && console.warn && Function.prototype.bind ?
297 Function.prototype.bind.call( console.warn, console ) :
298 function () {};
299
300 /**
301 * Write a message to the browser console's error channel.
302 *
303 * Most browsers also print a stacktrace when calling this method if the
304 * argument is an Error object.
305 *
306 * This method is a no-op in browsers that don't implement the Console API.
307 *
308 * @since 1.26
309 * @param {...Mixed} msg Messages to output to console
310 */
311 log.error = console && console.error && Function.prototype.bind ?
312 Function.prototype.bind.call( console.error, console ) :
313 function () {};
314
315 /**
316 * Create a property on a host object that, when accessed, will produce
317 * a deprecation warning in the console.
318 *
319 * @param {Object} obj Host object of deprecated property
320 * @param {string} key Name of property to create in `obj`
321 * @param {Mixed} val The value this property should return when accessed
322 * @param {string} [msg] Optional text to include in the deprecation message
323 * @param {string} [logName=key] Optional custom name for the feature.
324 * This is used instead of `key` in the message and `mw.deprecate` tracking.
325 */
326 log.deprecate = !Object.defineProperty ? function ( obj, key, val ) {
327 obj[ key ] = val;
328 } : function ( obj, key, val, msg, logName ) {
329 var logged = new StringSet();
330 logName = logName || key;
331 msg = 'Use of "' + logName + '" is deprecated.' + ( msg ? ( ' ' + msg ) : '' );
332 function uniqueTrace() {
333 var trace = new Error().stack;
334 if ( logged.has( trace ) ) {
335 return false;
336 }
337 logged.add( trace );
338 return true;
339 }
340 // Support: Safari 5.0
341 // Throws "not supported on DOM Objects" for Node or Element objects (incl. document)
342 // Safari 4.0 doesn't have this method, and it was fixed in Safari 5.1.
343 try {
344 Object.defineProperty( obj, key, {
345 configurable: true,
346 enumerable: true,
347 get: function () {
348 if ( uniqueTrace() ) {
349 mw.track( 'mw.deprecate', logName );
350 mw.log.warn( msg );
351 }
352 return val;
353 },
354 set: function ( newVal ) {
355 if ( uniqueTrace() ) {
356 mw.track( 'mw.deprecate', logName );
357 mw.log.warn( msg );
358 }
359 val = newVal;
360 }
361 } );
362 } catch ( err ) {
363 obj[ key ] = val;
364 }
365 };
366
367 return log;
368 }() );
369 /* eslint-enable no-console */
370
371 /**
372 * @class mw
373 */
374 mw = {
375 redefineFallbacksForTest: function () {
376 if ( !window.QUnit ) {
377 throw new Error( 'Reset not allowed outside unit tests' );
378 }
379 defineFallbacks();
380 },
381
382 /**
383 * Get the current time, measured in milliseconds since January 1, 1970 (UTC).
384 *
385 * On browsers that implement the Navigation Timing API, this function will produce floating-point
386 * values with microsecond precision that are guaranteed to be monotonic. On all other browsers,
387 * it will fall back to using `Date`.
388 *
389 * @return {number} Current time
390 */
391 now: ( function () {
392 var perf = window.performance,
393 navStart = perf && perf.timing && perf.timing.navigationStart;
394 return navStart && typeof perf.now === 'function' ?
395 function () { return navStart + perf.now(); } :
396 function () { return Date.now(); };
397 }() ),
398
399 /**
400 * List of all analytic events emitted so far.
401 *
402 * @private
403 * @property {Array}
404 */
405 trackQueue: trackQueue,
406
407 track: function ( topic, data ) {
408 trackQueue.push( { topic: topic, timeStamp: mw.now(), data: data } );
409 // The base module extends this method to fire events here
410 },
411
412 /**
413 * Track an early error event via mw.track and send it to the window console.
414 *
415 * @private
416 * @param {string} topic Topic name
417 * @param {Object} data Data describing the event, encoded as an object; see mw#logError
418 */
419 trackError: function ( topic, data ) {
420 mw.track( topic, data );
421 logError( topic, data );
422 },
423
424 // Expose Map constructor
425 Map: Map,
426
427 /**
428 * Map of configuration values.
429 *
430 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
431 * on mediawiki.org.
432 *
433 * If `$wgLegacyJavaScriptGlobals` is true, this Map will add its values to the
434 * global `window` object.
435 *
436 * @property {mw.Map} config
437 */
438 // Dummy placeholder later assigned in ResourceLoaderStartUpModule
439 config: null,
440
441 /**
442 * Empty object for third-party libraries, for cases where you don't
443 * want to add a new global, or the global is bad and needs containment
444 * or wrapping.
445 *
446 * @property
447 */
448 libs: {},
449
450 /**
451 * Access container for deprecated functionality that can be moved from
452 * from their legacy location and attached to this object (e.g. a global
453 * function that is deprecated and as stop-gap can be exposed through here).
454 *
455 * This was reserved for future use but never ended up being used.
456 *
457 * @deprecated since 1.22 Let deprecated identifiers keep their original name
458 * and use mw.log#deprecate to create an access container for tracking.
459 * @property
460 */
461 legacy: {},
462
463 /**
464 * Store for messages.
465 *
466 * @property {mw.Map}
467 */
468 messages: new Map(),
469
470 /**
471 * Store for templates associated with a module.
472 *
473 * @property {mw.Map}
474 */
475 templates: new Map(),
476
477 // Expose mw.log
478 log: log,
479
480 /**
481 * Client for ResourceLoader server end point.
482 *
483 * This client is in charge of maintaining the module registry and state
484 * machine, initiating network (batch) requests for loading modules, as
485 * well as dependency resolution and execution of source code.
486 *
487 * For more information, refer to
488 * <https://www.mediawiki.org/wiki/ResourceLoader/Features>
489 *
490 * @class mw.loader
491 * @singleton
492 */
493 loader: ( function () {
494
495 /**
496 * Fired via mw.track on various resource loading errors.
497 *
498 * @event resourceloader_exception
499 * @param {Error|Mixed} e The error that was thrown. Almost always an Error
500 * object, but in theory module code could manually throw something else, and that
501 * might also end up here.
502 * @param {string} [module] Name of the module which caused the error. Omitted if the
503 * error is not module-related or the module cannot be easily identified due to
504 * batched handling.
505 * @param {string} source Source of the error. Possible values:
506 *
507 * - style: stylesheet error (only affects old IE where a special style loading method
508 * is used)
509 * - load-callback: exception thrown by user callback
510 * - module-execute: exception thrown by module code
511 * - resolve: failed to sort dependencies for a module in mw.loader.load
512 * - store-eval: could not evaluate module code cached in localStorage
513 * - store-localstorage-init: localStorage or JSON parse error in mw.loader.store.init
514 * - store-localstorage-json: JSON conversion error in mw.loader.store.set
515 * - store-localstorage-update: localStorage or JSON conversion error in mw.loader.store.update
516 */
517
518 /**
519 * Fired via mw.track on resource loading error conditions.
520 *
521 * @event resourceloader_assert
522 * @param {string} source Source of the error. Possible values:
523 *
524 * - bug-T59567: failed to cache script due to an Opera function -> string conversion
525 * bug; see <https://phabricator.wikimedia.org/T59567> for details
526 */
527
528 /**
529 * Mapping of registered modules.
530 *
531 * See #implement and #execute for exact details on support for script, style and messages.
532 *
533 * Format:
534 *
535 * {
536 * 'moduleName': {
537 * // From mw.loader.register()
538 * 'version': '########' (hash)
539 * 'dependencies': ['required.foo', 'bar.also', ...]
540 * 'group': 'somegroup', (or) null
541 * 'source': 'local', (or) 'anotherwiki'
542 * 'skip': 'return !!window.Example', (or) null
543 * 'module': export Object
544 *
545 * // Set from execute() or mw.loader.state()
546 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error', or 'missing'
547 *
548 * // Optionally added at run-time by mw.loader.implement()
549 * 'skipped': true
550 * 'script': closure, array of urls, or string
551 * 'style': { ... } (see #execute)
552 * 'messages': { 'key': 'value', ... }
553 * }
554 * }
555 *
556 * State machine:
557 *
558 * - `registered`:
559 * The module is known to the system but not yet required.
560 * Meta data is registered via mw.loader#register. Calls to that method are
561 * generated server-side by the startup module.
562 * - `loading`:
563 * The module was required through mw.loader (either directly or as dependency of
564 * another module). The client will fetch module contents from the server.
565 * The contents are then stashed in the registry via mw.loader#implement.
566 * - `loaded`:
567 * The module has been loaded from the server and stashed via mw.loader#implement.
568 * If the module has no more dependencies in-flight, the module will be executed
569 * immediately. Otherwise execution is deferred, controlled via #handlePending.
570 * - `executing`:
571 * The module is being executed.
572 * - `ready`:
573 * The module has been successfully executed.
574 * - `error`:
575 * The module (or one of its dependencies) produced an error during execution.
576 * - `missing`:
577 * The module was registered client-side and requested, but the server denied knowledge
578 * of the module's existence.
579 *
580 * @property
581 * @private
582 */
583 var registry = {},
584 // Mapping of sources, keyed by source-id, values are strings.
585 //
586 // Format:
587 //
588 // {
589 // 'sourceId': 'http://example.org/w/load.php'
590 // }
591 //
592 sources = {},
593
594 // For queueModuleScript()
595 handlingPendingRequests = false,
596 pendingRequests = [],
597
598 // List of modules to be loaded
599 queue = [],
600
601 /**
602 * List of callback jobs waiting for modules to be ready.
603 *
604 * Jobs are created by #enqueue() and run by #handlePending().
605 *
606 * Typically when a job is created for a module, the job's dependencies contain
607 * both the required module and all its recursive dependencies.
608 *
609 * Format:
610 *
611 * {
612 * 'dependencies': [ module names ],
613 * 'ready': Function callback
614 * 'error': Function callback
615 * }
616 *
617 * @property {Object[]} jobs
618 * @private
619 */
620 jobs = [],
621
622 /**
623 * @private
624 * @property {Array} baseModules
625 */
626 baseModules = $VARS.baseModules,
627
628 /**
629 * For #addEmbeddedCSS() and #addLink()
630 *
631 * @private
632 * @property {HTMLElement|null} marker
633 */
634 marker = document.querySelector( 'meta[name="ResourceLoaderDynamicStyles"]' ),
635
636 // For addEmbeddedCSS()
637 cssBuffer = '',
638 cssBufferTimer = null,
639 cssCallbacks = [],
640 rAF = window.requestAnimationFrame || setTimeout;
641
642 /**
643 * Create a new style element and add it to the DOM.
644 *
645 * @private
646 * @param {string} text CSS text
647 * @param {Node|null} [nextNode] The element where the style tag
648 * should be inserted before
649 * @return {HTMLElement} Reference to the created style element
650 */
651 function newStyleTag( text, nextNode ) {
652 var el = document.createElement( 'style' );
653 el.appendChild( document.createTextNode( text ) );
654 if ( nextNode && nextNode.parentNode ) {
655 nextNode.parentNode.insertBefore( el, nextNode );
656 } else {
657 document.head.appendChild( el );
658 }
659 return el;
660 }
661
662 /**
663 * Add a bit of CSS text to the current browser page.
664 *
665 * The CSS will be appended to an existing ResourceLoader-created `<style>` tag
666 * or create a new one based on whether the given `cssText` is safe for extension.
667 *
668 * @private
669 * @param {string} [cssText=cssBuffer] If called without cssText,
670 * the internal buffer will be inserted instead.
671 * @param {Function} [callback]
672 */
673 function addEmbeddedCSS( cssText, callback ) {
674 function fireCallbacks() {
675 var i,
676 oldCallbacks = cssCallbacks;
677 // Reset cssCallbacks variable so it's not polluted by any calls to
678 // addEmbeddedCSS() from one of the callbacks (T105973)
679 cssCallbacks = [];
680 for ( i = 0; i < oldCallbacks.length; i++ ) {
681 oldCallbacks[ i ]();
682 }
683 }
684
685 if ( callback ) {
686 cssCallbacks.push( callback );
687 }
688
689 // Yield once before creating the <style> tag. This lets multiple stylesheets
690 // accumulate into one buffer, allowing us to reduce how often new stylesheets
691 // are inserted in the browser. Appending a stylesheet and waiting for the
692 // browser to repaint is fairly expensive. (T47810)
693 if ( cssText ) {
694 // Don't extend the buffer if the item needs its own stylesheet.
695 // Keywords like `@import` are only valid at the start of a stylesheet (T37562).
696 if ( !cssBuffer || cssText.slice( 0, '@import'.length ) !== '@import' ) {
697 // Linebreak for somewhat distinguishable sections
698 cssBuffer += '\n' + cssText;
699 if ( !cssBufferTimer ) {
700 cssBufferTimer = rAF( function () {
701 // Wrap in anonymous function that takes no arguments
702 // Support: Firefox < 13
703 // Firefox 12 has non-standard behaviour of passing a number
704 // as first argument to a setTimeout callback.
705 // http://benalman.com/news/2009/07/the-mysterious-firefox-settime/
706 addEmbeddedCSS();
707 } );
708 }
709 return;
710 }
711
712 // This is a scheduled flush for the buffer
713 } else {
714 cssBufferTimer = null;
715 cssText = cssBuffer;
716 cssBuffer = '';
717 }
718
719 newStyleTag( cssText, marker );
720
721 fireCallbacks();
722 }
723
724 /**
725 * @private
726 * @param {Array} modules List of module names
727 * @return {string} Hash of concatenated version hashes.
728 */
729 function getCombinedVersion( modules ) {
730 var hashes = modules.reduce( function ( result, module ) {
731 return result + registry[ module ].version;
732 }, '' );
733 return fnv132( hashes );
734 }
735
736 /**
737 * Determine whether all dependencies are in state 'ready', which means we may
738 * execute the module or job now.
739 *
740 * @private
741 * @param {Array} modules Names of modules to be checked
742 * @return {boolean} True if all modules are in state 'ready', false otherwise
743 */
744 function allReady( modules ) {
745 var i;
746 for ( i = 0; i < modules.length; i++ ) {
747 if ( mw.loader.getState( modules[ i ] ) !== 'ready' ) {
748 return false;
749 }
750 }
751 return true;
752 }
753
754 /**
755 * Determine whether all direct and base dependencies are in state 'ready'
756 *
757 * @private
758 * @param {string} module Name of the module to be checked
759 * @return {boolean} True if all direct/base dependencies are in state 'ready'; false otherwise
760 */
761 function allWithImplicitReady( module ) {
762 return allReady( registry[ module ].dependencies ) &&
763 ( baseModules.indexOf( module ) !== -1 || allReady( baseModules ) );
764 }
765
766 /**
767 * Determine whether all dependencies are in state 'ready', which means we may
768 * execute the module or job now.
769 *
770 * @private
771 * @param {Array} modules Names of modules to be checked
772 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
773 */
774 function anyFailed( modules ) {
775 var i, state;
776 for ( i = 0; i < modules.length; i++ ) {
777 state = mw.loader.getState( modules[ i ] );
778 if ( state === 'error' || state === 'missing' ) {
779 return true;
780 }
781 }
782 return false;
783 }
784
785 /**
786 * A module has entered state 'ready', 'error', or 'missing'. Automatically update
787 * pending jobs and modules that depend upon this module. If the given module failed,
788 * propagate the 'error' state up the dependency tree. Otherwise, go ahead and execute
789 * all jobs/modules now having their dependencies satisfied.
790 *
791 * Jobs that depend on a failed module, will have their error callback ran (if any).
792 *
793 * @private
794 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
795 */
796 function handlePending( module ) {
797 var j, job, hasErrors, m, stateChange, fromBaseModule;
798
799 if ( registry[ module ].state === 'error' || registry[ module ].state === 'missing' ) {
800 fromBaseModule = baseModules.indexOf( module ) !== -1;
801 // If the current module failed, mark all dependent modules also as failed.
802 // Iterate until steady-state to propagate the error state upwards in the
803 // dependency tree.
804 do {
805 stateChange = false;
806 for ( m in registry ) {
807 if ( registry[ m ].state !== 'error' && registry[ m ].state !== 'missing' ) {
808 // Always propagate errors from base modules to regular modules (implicit dependency).
809 // Between base modules or regular modules, consider direct dependencies only.
810 if (
811 ( fromBaseModule && baseModules.indexOf( m ) === -1 ) ||
812 anyFailed( registry[ m ].dependencies )
813 ) {
814 registry[ m ].state = 'error';
815 stateChange = true;
816 }
817 }
818 }
819 } while ( stateChange );
820 }
821
822 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
823 for ( j = 0; j < jobs.length; j++ ) {
824 hasErrors = anyFailed( jobs[ j ].dependencies );
825 if ( hasErrors || allReady( jobs[ j ].dependencies ) ) {
826 // All dependencies satisfied, or some have errors
827 job = jobs[ j ];
828 jobs.splice( j, 1 );
829 j -= 1;
830 try {
831 if ( hasErrors ) {
832 if ( typeof job.error === 'function' ) {
833 job.error( new Error( 'Module ' + module + ' has failed dependencies' ), [ module ] );
834 }
835 } else {
836 if ( typeof job.ready === 'function' ) {
837 job.ready();
838 }
839 }
840 } catch ( e ) {
841 // A user-defined callback raised an exception.
842 // Swallow it to protect our state machine!
843 mw.trackError( 'resourceloader.exception', {
844 exception: e,
845 module: module,
846 source: 'load-callback'
847 } );
848 }
849 }
850 }
851
852 // The current module became 'ready'.
853 if ( registry[ module ].state === 'ready' ) {
854 // Save it to the module store.
855 mw.loader.store.set( module, registry[ module ] );
856 // Recursively execute all dependent modules that were already loaded
857 // (waiting for execution) and no longer have unsatisfied dependencies.
858 for ( m in registry ) {
859 // Base modules may have dependencies amongst eachother to ensure correct
860 // execution order. Regular modules wait for all base modules.
861 if ( registry[ m ].state === 'loaded' && allWithImplicitReady( m ) ) {
862 // eslint-disable-next-line no-use-before-define
863 execute( m );
864 }
865 }
866 }
867 }
868
869 /**
870 * Resolve dependencies and detect circular references.
871 *
872 * @private
873 * @param {string} module Name of the top-level module whose dependencies shall be
874 * resolved and sorted.
875 * @param {Array} resolved Returns a topological sort of the given module and its
876 * dependencies, such that later modules depend on earlier modules. The array
877 * contains the module names. If the array contains already some module names,
878 * this function appends its result to the pre-existing array.
879 * @param {StringSet} [unresolved] Used to track the current dependency
880 * chain, and to report loops in the dependency graph.
881 * @throws {Error} If any unregistered module or a dependency loop is encountered
882 */
883 function sortDependencies( module, resolved, unresolved ) {
884 var i, deps, skip;
885
886 if ( !hasOwn.call( registry, module ) ) {
887 throw new Error( 'Unknown dependency: ' + module );
888 }
889
890 if ( registry[ module ].skip !== null ) {
891 // eslint-disable-next-line no-new-func
892 skip = new Function( registry[ module ].skip );
893 registry[ module ].skip = null;
894 if ( skip() ) {
895 registry[ module ].skipped = true;
896 registry[ module ].dependencies = [];
897 registry[ module ].state = 'ready';
898 handlePending( module );
899 return;
900 }
901 }
902
903 if ( resolved.indexOf( module ) !== -1 ) {
904 // Module already resolved; nothing to do
905 return;
906 }
907 // Create unresolved if not passed in
908 if ( !unresolved ) {
909 unresolved = new StringSet();
910 }
911
912 // Add base modules
913 if ( baseModules.indexOf( module ) === -1 ) {
914 baseModules.forEach( function ( baseModule ) {
915 if ( resolved.indexOf( baseModule ) === -1 ) {
916 resolved.push( baseModule );
917 }
918 } );
919 }
920
921 // Tracks down dependencies
922 deps = registry[ module ].dependencies;
923 unresolved.add( module );
924 for ( i = 0; i < deps.length; i++ ) {
925 if ( resolved.indexOf( deps[ i ] ) === -1 ) {
926 if ( unresolved.has( deps[ i ] ) ) {
927 throw new Error(
928 'Circular reference detected: ' + module + ' -> ' + deps[ i ]
929 );
930 }
931
932 sortDependencies( deps[ i ], resolved, unresolved );
933 }
934 }
935 resolved.push( module );
936 }
937
938 /**
939 * Get names of module that a module depends on, in their proper dependency order.
940 *
941 * @private
942 * @param {string[]} modules Array of string module names
943 * @return {Array} List of dependencies, including 'module'.
944 * @throws {Error} If an unregistered module or a dependency loop is encountered
945 */
946 function resolve( modules ) {
947 var i, resolved = [];
948 for ( i = 0; i < modules.length; i++ ) {
949 sortDependencies( modules[ i ], resolved );
950 }
951 return resolved;
952 }
953
954 /**
955 * Like #resolve(), except it will silently ignore modules that
956 * are missing or have missing dependencies.
957 *
958 * @private
959 * @param {string[]} modules Array of string module names
960 * @return {Array} List of dependencies.
961 */
962 function resolveStubbornly( modules ) {
963 var i, saved, resolved = [];
964 for ( i = 0; i < modules.length; i++ ) {
965 saved = resolved.slice();
966 try {
967 sortDependencies( modules[ i ], resolved );
968 } catch ( err ) {
969 // This module is unknown or has unknown dependencies.
970 // Undo any incomplete resolutions made and keep going.
971 resolved = saved;
972 mw.trackError( 'resourceloader.exception', {
973 exception: err,
974 source: 'resolve'
975 } );
976 }
977 }
978 return resolved;
979 }
980
981 /**
982 * Load and execute a script.
983 *
984 * @private
985 * @param {string} src URL to script, will be used as the src attribute in the script tag
986 * @param {Function} [callback] Callback to run after request resolution
987 */
988 function addScript( src, callback ) {
989 var script = document.createElement( 'script' );
990 script.src = src;
991 script.onload = script.onerror = function () {
992 if ( script.parentNode ) {
993 script.parentNode.removeChild( script );
994 }
995 script = null;
996 if ( callback ) {
997 callback();
998 callback = null;
999 }
1000 };
1001 document.head.appendChild( script );
1002 }
1003
1004 /**
1005 * Queue the loading and execution of a script for a particular module.
1006 *
1007 * This does for debug mode what runScript() does for production.
1008 *
1009 * @private
1010 * @param {string} src URL of the script
1011 * @param {string} moduleName Name of currently executing module
1012 * @param {Function} callback Callback to run after addScript() resolution
1013 */
1014 function queueModuleScript( src, moduleName, callback ) {
1015 pendingRequests.push( function () {
1016 // Keep in sync with execute()/runScript().
1017 if ( moduleName !== 'jquery' && hasOwn.call( registry, moduleName ) ) {
1018 window.require = mw.loader.require;
1019 window.module = registry[ moduleName ].module;
1020 }
1021 addScript( src, function () {
1022 // 'module.exports' should not persist after the file is executed to
1023 // avoid leakage to unrelated code. 'require' should be kept, however,
1024 // as asynchronous access to 'require' is allowed and expected. (T144879)
1025 delete window.module;
1026 callback();
1027 // Start the next one (if any)
1028 if ( pendingRequests[ 0 ] ) {
1029 pendingRequests.shift()();
1030 } else {
1031 handlingPendingRequests = false;
1032 }
1033 } );
1034 } );
1035 if ( !handlingPendingRequests && pendingRequests[ 0 ] ) {
1036 handlingPendingRequests = true;
1037 pendingRequests.shift()();
1038 }
1039 }
1040
1041 /**
1042 * Utility function for execute()
1043 *
1044 * @ignore
1045 * @param {string} [media] Media attribute
1046 * @param {string} url URL
1047 */
1048 function addLink( media, url ) {
1049 var el = document.createElement( 'link' );
1050
1051 el.rel = 'stylesheet';
1052 if ( media && media !== 'all' ) {
1053 el.media = media;
1054 }
1055 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1056 // see #addEmbeddedCSS, T33676, T43331, and T49277 for details.
1057 el.href = url;
1058
1059 if ( marker && marker.parentNode ) {
1060 marker.parentNode.insertBefore( el, marker );
1061 } else {
1062 document.head.appendChild( el );
1063 }
1064 }
1065
1066 /**
1067 * @private
1068 * @param {string} code JavaScript code
1069 */
1070 function domEval( code ) {
1071 var script = document.createElement( 'script' );
1072 if ( mw.config.get( 'wgCSPNonce' ) !== false ) {
1073 script.nonce = mw.config.get( 'wgCSPNonce' );
1074 }
1075 script.text = code;
1076 document.head.appendChild( script );
1077 script.parentNode.removeChild( script );
1078 }
1079
1080 /**
1081 * Add one or more modules to the module load queue.
1082 *
1083 * See also #work().
1084 *
1085 * @private
1086 * @param {string[]} dependencies Array of module names in the registry
1087 * @param {Function} [ready] Callback to execute when all dependencies are ready
1088 * @param {Function} [error] Callback to execute when any dependency fails
1089 */
1090 function enqueue( dependencies, ready, error ) {
1091 if ( allReady( dependencies ) ) {
1092 // Run ready immediately
1093 if ( ready !== undefined ) {
1094 ready();
1095 }
1096 return;
1097 }
1098
1099 if ( anyFailed( dependencies ) ) {
1100 if ( error !== undefined ) {
1101 // Execute error immediately if any dependencies have errors
1102 error(
1103 new Error( 'One or more dependencies failed to load' ),
1104 dependencies
1105 );
1106 }
1107 return;
1108 }
1109
1110 // Not all dependencies are ready, add to the load queue...
1111
1112 // Add ready and error callbacks if they were given
1113 if ( ready !== undefined || error !== undefined ) {
1114 jobs.push( {
1115 // Narrow down the list to modules that are worth waiting for
1116 dependencies: dependencies.filter( function ( module ) {
1117 var state = registry[ module ].state;
1118 return state === 'registered' || state === 'loaded' || state === 'loading' || state === 'executing';
1119 } ),
1120 ready: ready,
1121 error: error
1122 } );
1123 }
1124
1125 dependencies.forEach( function ( module ) {
1126 // Only queue modules that are still in the initial 'registered' state
1127 // (not ones already loading, ready or error).
1128 if ( registry[ module ].state === 'registered' && queue.indexOf( module ) === -1 ) {
1129 // Private modules must be embedded in the page. Don't bother queuing
1130 // these as the server will deny them anyway (T101806).
1131 if ( registry[ module ].group === 'private' ) {
1132 registry[ module ].state = 'error';
1133 handlePending( module );
1134 return;
1135 }
1136 queue.push( module );
1137 }
1138 } );
1139
1140 mw.loader.work();
1141 }
1142
1143 /**
1144 * Executes a loaded module, making it ready to use
1145 *
1146 * @private
1147 * @param {string} module Module name to execute
1148 */
1149 function execute( module ) {
1150 var key, value, media, i, urls, cssHandle, checkCssHandles, runScript,
1151 cssHandlesRegistered = false;
1152
1153 if ( !hasOwn.call( registry, module ) ) {
1154 throw new Error( 'Module has not been registered yet: ' + module );
1155 }
1156 if ( registry[ module ].state !== 'loaded' ) {
1157 throw new Error( 'Module in state "' + registry[ module ].state + '" may not be executed: ' + module );
1158 }
1159
1160 registry[ module ].state = 'executing';
1161 $CODE.profileExecuteStart();
1162
1163 runScript = function () {
1164 var script, markModuleReady, nestedAddScript;
1165
1166 $CODE.profileScriptStart();
1167 script = registry[ module ].script;
1168 markModuleReady = function () {
1169 $CODE.profileScriptEnd();
1170 registry[ module ].state = 'ready';
1171 handlePending( module );
1172 };
1173 nestedAddScript = function ( arr, callback, i ) {
1174 // Recursively call queueModuleScript() in its own callback
1175 // for each element of arr.
1176 if ( i >= arr.length ) {
1177 // We're at the end of the array
1178 callback();
1179 return;
1180 }
1181
1182 queueModuleScript( arr[ i ], module, function () {
1183 nestedAddScript( arr, callback, i + 1 );
1184 } );
1185 };
1186
1187 try {
1188 if ( Array.isArray( script ) ) {
1189 nestedAddScript( script, markModuleReady, 0 );
1190 } else if ( typeof script === 'function' ) {
1191 // Keep in sync with queueModuleScript() for debug mode
1192 if ( module === 'jquery' ) {
1193 // This is a special case for when 'jquery' itself is being loaded.
1194 // - The standard jquery.js distribution does not set `window.jQuery`
1195 // in CommonJS-compatible environments (Node.js, AMD, RequireJS, etc.).
1196 // - MediaWiki's 'jquery' module also bundles jquery.migrate.js, which
1197 // in a CommonJS-compatible environment, will use require('jquery'),
1198 // but that can't work when we're still inside that module.
1199 script();
1200 } else {
1201 // Pass jQuery twice so that the signature of the closure which wraps
1202 // the script can bind both '$' and 'jQuery'.
1203 script( window.$, window.$, mw.loader.require, registry[ module ].module );
1204 }
1205 markModuleReady();
1206
1207 } else if ( typeof script === 'string' ) {
1208 // Site and user modules are legacy scripts that run in the global scope.
1209 // This is transported as a string instead of a function to avoid needing
1210 // to use string manipulation to undo the function wrapper.
1211 domEval( script );
1212 markModuleReady();
1213
1214 } else {
1215 // Module without script
1216 markModuleReady();
1217 }
1218 } catch ( e ) {
1219 // Use mw.track instead of mw.log because these errors are common in production mode
1220 // (e.g. undefined variable), and mw.log is only enabled in debug mode.
1221 registry[ module ].state = 'error';
1222 $CODE.profileScriptEnd();
1223 mw.trackError( 'resourceloader.exception', {
1224 exception: e, module:
1225 module, source: 'module-execute'
1226 } );
1227 handlePending( module );
1228 }
1229 };
1230
1231 // Add localizations to message system
1232 if ( registry[ module ].messages ) {
1233 mw.messages.set( registry[ module ].messages );
1234 }
1235
1236 // Initialise templates
1237 if ( registry[ module ].templates ) {
1238 mw.templates.set( module, registry[ module ].templates );
1239 }
1240
1241 // Make sure we don't run the scripts until all stylesheet insertions have completed.
1242 ( function () {
1243 var pending = 0;
1244 checkCssHandles = function () {
1245 var ex, dependencies;
1246 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
1247 // one of the cssHandles is fired while we're still creating more handles.
1248 if ( cssHandlesRegistered && pending === 0 && runScript ) {
1249 if ( module === 'user' ) {
1250 // Implicit dependency on the site module. Not real dependency because
1251 // it should run after 'site' regardless of whether it succeeds or fails.
1252 // Note: This is a simplified version of mw.loader.using(), inlined here
1253 // as using() depends on jQuery (T192623).
1254 try {
1255 dependencies = resolve( [ 'site' ] );
1256 } catch ( e ) {
1257 ex = e;
1258 runScript();
1259 }
1260 if ( ex === undefined ) {
1261 enqueue( dependencies, runScript, runScript );
1262 }
1263 } else {
1264 runScript();
1265 }
1266 runScript = undefined; // Revoke
1267 }
1268 };
1269 cssHandle = function () {
1270 var check = checkCssHandles;
1271 pending++;
1272 return function () {
1273 if ( check ) {
1274 pending--;
1275 check();
1276 check = undefined; // Revoke
1277 }
1278 };
1279 };
1280 }() );
1281
1282 // Process styles (see also mw.loader.implement)
1283 // * back-compat: { <media>: css }
1284 // * back-compat: { <media>: [url, ..] }
1285 // * { "css": [css, ..] }
1286 // * { "url": { <media>: [url, ..] } }
1287 if ( registry[ module ].style ) {
1288 for ( key in registry[ module ].style ) {
1289 value = registry[ module ].style[ key ];
1290 media = undefined;
1291
1292 if ( key !== 'url' && key !== 'css' ) {
1293 // Backwards compatibility, key is a media-type
1294 if ( typeof value === 'string' ) {
1295 // back-compat: { <media>: css }
1296 // Ignore 'media' because it isn't supported (nor was it used).
1297 // Strings are pre-wrapped in "@media". The media-type was just ""
1298 // (because it had to be set to something).
1299 // This is one of the reasons why this format is no longer used.
1300 addEmbeddedCSS( value, cssHandle() );
1301 } else {
1302 // back-compat: { <media>: [url, ..] }
1303 media = key;
1304 key = 'bc-url';
1305 }
1306 }
1307
1308 // Array of css strings in key 'css',
1309 // or back-compat array of urls from media-type
1310 if ( Array.isArray( value ) ) {
1311 for ( i = 0; i < value.length; i++ ) {
1312 if ( key === 'bc-url' ) {
1313 // back-compat: { <media>: [url, ..] }
1314 addLink( media, value[ i ] );
1315 } else if ( key === 'css' ) {
1316 // { "css": [css, ..] }
1317 addEmbeddedCSS( value[ i ], cssHandle() );
1318 }
1319 }
1320 // Not an array, but a regular object
1321 // Array of urls inside media-type key
1322 } else if ( typeof value === 'object' ) {
1323 // { "url": { <media>: [url, ..] } }
1324 for ( media in value ) {
1325 urls = value[ media ];
1326 for ( i = 0; i < urls.length; i++ ) {
1327 addLink( media, urls[ i ] );
1328 }
1329 }
1330 }
1331 }
1332 }
1333
1334 // End profiling of execute()-self before we call checkCssHandles(),
1335 // which (sometimes asynchronously) calls runScript(), which we want
1336 // to measure separately without overlap.
1337 $CODE.profileExecuteEnd();
1338
1339 // Kick off.
1340 cssHandlesRegistered = true;
1341 checkCssHandles();
1342 }
1343
1344 function sortQuery( o ) {
1345 var key,
1346 sorted = {},
1347 a = [];
1348
1349 for ( key in o ) {
1350 a.push( key );
1351 }
1352 a.sort();
1353 for ( key = 0; key < a.length; key++ ) {
1354 sorted[ a[ key ] ] = o[ a[ key ] ];
1355 }
1356 return sorted;
1357 }
1358
1359 /**
1360 * Converts a module map of the form `{ foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }`
1361 * to a query string of the form `foo.bar,baz|bar.baz,quux`.
1362 *
1363 * See `ResourceLoader::makePackedModulesString()` in PHP, of which this is a port.
1364 * On the server, unpacking is done by `ResourceLoaderContext::expandModuleNames()`.
1365 *
1366 * Note: This is only half of the logic, the other half has to be in #batchRequest(),
1367 * because its implementation needs to keep track of potential string size in order
1368 * to decide when to split the requests due to url size.
1369 *
1370 * @private
1371 * @param {Object} moduleMap Module map
1372 * @return {Object}
1373 * @return {string} return.str Module query string
1374 * @return {Array} return.list List of module names in matching order
1375 */
1376 function buildModulesString( moduleMap ) {
1377 var p, prefix,
1378 str = [],
1379 list = [];
1380
1381 function restore( suffix ) {
1382 return p + suffix;
1383 }
1384
1385 for ( prefix in moduleMap ) {
1386 p = prefix === '' ? '' : prefix + '.';
1387 str.push( p + moduleMap[ prefix ].join( ',' ) );
1388 list.push.apply( list, moduleMap[ prefix ].map( restore ) );
1389 }
1390 return {
1391 str: str.join( '|' ),
1392 list: list
1393 };
1394 }
1395
1396 /**
1397 * Resolve indexed dependencies.
1398 *
1399 * ResourceLoader uses an optimization to save space which replaces module names in
1400 * dependency lists with the index of that module within the array of module
1401 * registration data if it exists. The benefit is a significant reduction in the data
1402 * size of the startup module. This function changes those dependency lists back to
1403 * arrays of strings.
1404 *
1405 * @private
1406 * @param {Array} modules Modules array
1407 */
1408 function resolveIndexedDependencies( modules ) {
1409 var i, j, deps;
1410 function resolveIndex( dep ) {
1411 return typeof dep === 'number' ? modules[ dep ][ 0 ] : dep;
1412 }
1413 for ( i = 0; i < modules.length; i++ ) {
1414 deps = modules[ i ][ 2 ];
1415 if ( deps ) {
1416 for ( j = 0; j < deps.length; j++ ) {
1417 deps[ j ] = resolveIndex( deps[ j ] );
1418 }
1419 }
1420 }
1421 }
1422
1423 /**
1424 * @private
1425 * @param {Object} params Map of parameter names to values
1426 * @return {string}
1427 */
1428 function makeQueryString( params ) {
1429 return Object.keys( params ).map( function ( key ) {
1430 return encodeURIComponent( key ) + '=' + encodeURIComponent( params[ key ] );
1431 } ).join( '&' );
1432 }
1433
1434 /**
1435 * Create network requests for a batch of modules.
1436 *
1437 * This is an internal method for #work(). This must not be called directly
1438 * unless the modules are already registered, and no request is in progress,
1439 * and the module state has already been set to `loading`.
1440 *
1441 * @private
1442 * @param {string[]} batch
1443 */
1444 function batchRequest( batch ) {
1445 var reqBase, splits, maxQueryLength, b, bSource, bGroup,
1446 source, group, i, modules, sourceLoadScript,
1447 currReqBase, currReqBaseLength, moduleMap, currReqModules, l,
1448 lastDotIndex, prefix, suffix, bytesAdded;
1449
1450 /**
1451 * Start the currently drafted request to the server.
1452 *
1453 * @ignore
1454 */
1455 function doRequest() {
1456 // Optimisation: Inherit (Object.create), not copy ($.extend)
1457 var query = Object.create( currReqBase ),
1458 packed = buildModulesString( moduleMap );
1459 query.modules = packed.str;
1460 // The packing logic can change the effective order, even if the input was
1461 // sorted. As such, the call to getCombinedVersion() must use this
1462 // effective order, instead of currReqModules, as otherwise the combined
1463 // version will not match the hash expected by the server based on
1464 // combining versions from the module query string in-order. (T188076)
1465 query.version = getCombinedVersion( packed.list );
1466 query = sortQuery( query );
1467 addScript( sourceLoadScript + '?' + makeQueryString( query ) );
1468 }
1469
1470 if ( !batch.length ) {
1471 return;
1472 }
1473
1474 // Always order modules alphabetically to help reduce cache
1475 // misses for otherwise identical content.
1476 batch.sort();
1477
1478 // Query parameters common to all requests
1479 reqBase = {
1480 skin: mw.config.get( 'skin' ),
1481 lang: mw.config.get( 'wgUserLanguage' ),
1482 debug: mw.config.get( 'debug' )
1483 };
1484 maxQueryLength = mw.config.get( 'wgResourceLoaderMaxQueryLength', 2000 );
1485
1486 // Split module list by source and by group.
1487 splits = Object.create( null );
1488 for ( b = 0; b < batch.length; b++ ) {
1489 bSource = registry[ batch[ b ] ].source;
1490 bGroup = registry[ batch[ b ] ].group;
1491 if ( !splits[ bSource ] ) {
1492 splits[ bSource ] = Object.create( null );
1493 }
1494 if ( !splits[ bSource ][ bGroup ] ) {
1495 splits[ bSource ][ bGroup ] = [];
1496 }
1497 splits[ bSource ][ bGroup ].push( batch[ b ] );
1498 }
1499
1500 for ( source in splits ) {
1501 sourceLoadScript = sources[ source ];
1502
1503 for ( group in splits[ source ] ) {
1504
1505 // Cache access to currently selected list of
1506 // modules for this group from this source.
1507 modules = splits[ source ][ group ];
1508
1509 // Query parameters common to requests for this module group
1510 // Optimisation: Inherit (Object.create), not copy ($.extend)
1511 currReqBase = Object.create( reqBase );
1512 // User modules require a user name in the query string.
1513 if ( group === 'user' && mw.config.get( 'wgUserName' ) !== null ) {
1514 currReqBase.user = mw.config.get( 'wgUserName' );
1515 }
1516
1517 // In addition to currReqBase, doRequest() will also add 'modules' and 'version'.
1518 // > '&modules='.length === 9
1519 // > '&version=1234567'.length === 16
1520 // > 9 + 16 = 25
1521 currReqBaseLength = makeQueryString( currReqBase ).length + 25;
1522
1523 // We may need to split up the request to honor the query string length limit,
1524 // so build it piece by piece.
1525 l = currReqBaseLength;
1526 moduleMap = Object.create( null ); // { prefix: [ suffixes ] }
1527 currReqModules = [];
1528
1529 for ( i = 0; i < modules.length; i++ ) {
1530 // Determine how many bytes this module would add to the query string
1531 lastDotIndex = modules[ i ].lastIndexOf( '.' );
1532 // If lastDotIndex is -1, substr() returns an empty string
1533 prefix = modules[ i ].substr( 0, lastDotIndex );
1534 suffix = modules[ i ].slice( lastDotIndex + 1 );
1535 bytesAdded = moduleMap[ prefix ] ?
1536 suffix.length + 3 : // '%2C'.length == 3
1537 modules[ i ].length + 3; // '%7C'.length == 3
1538
1539 // If the url would become too long, create a new one, but don't create empty requests
1540 if ( maxQueryLength > 0 && currReqModules.length && l + bytesAdded > maxQueryLength ) {
1541 // Dispatch what we've got...
1542 doRequest();
1543 // .. and start again.
1544 l = currReqBaseLength;
1545 moduleMap = Object.create( null );
1546 currReqModules = [];
1547
1548 mw.track( 'resourceloader.splitRequest', { maxQueryLength: maxQueryLength } );
1549 }
1550 if ( !moduleMap[ prefix ] ) {
1551 moduleMap[ prefix ] = [];
1552 }
1553 l += bytesAdded;
1554 moduleMap[ prefix ].push( suffix );
1555 currReqModules.push( modules[ i ] );
1556 }
1557 // If there's anything left in moduleMap, request that too
1558 if ( currReqModules.length ) {
1559 doRequest();
1560 }
1561 }
1562 }
1563 }
1564
1565 /**
1566 * @private
1567 * @param {string[]} implementations Array containing pieces of JavaScript code in the
1568 * form of calls to mw.loader#implement().
1569 * @param {Function} cb Callback in case of failure
1570 * @param {Error} cb.err
1571 */
1572 function asyncEval( implementations, cb ) {
1573 if ( !implementations.length ) {
1574 return;
1575 }
1576 mw.requestIdleCallback( function () {
1577 try {
1578 domEval( implementations.join( ';' ) );
1579 } catch ( err ) {
1580 cb( err );
1581 }
1582 } );
1583 }
1584
1585 /**
1586 * Make a versioned key for a specific module.
1587 *
1588 * @private
1589 * @param {string} module Module name
1590 * @return {string|null} Module key in format '`[name]@[version]`',
1591 * or null if the module does not exist
1592 */
1593 function getModuleKey( module ) {
1594 return hasOwn.call( registry, module ) ?
1595 ( module + '@' + registry[ module ].version ) : null;
1596 }
1597
1598 /**
1599 * @private
1600 * @param {string} key Module name or '`[name]@[version]`'
1601 * @return {Object}
1602 */
1603 function splitModuleKey( key ) {
1604 var index = key.indexOf( '@' );
1605 if ( index === -1 ) {
1606 return {
1607 name: key,
1608 version: ''
1609 };
1610 }
1611 return {
1612 name: key.slice( 0, index ),
1613 version: key.slice( index + 1 )
1614 };
1615 }
1616
1617 /* Public Members */
1618 return {
1619 /**
1620 * The module registry is exposed as an aid for debugging and inspecting page
1621 * state; it is not a public interface for modifying the registry.
1622 *
1623 * @see #registry
1624 * @property
1625 * @private
1626 */
1627 moduleRegistry: registry,
1628
1629 /**
1630 * @inheritdoc #newStyleTag
1631 * @method
1632 */
1633 addStyleTag: newStyleTag,
1634
1635 enqueue: enqueue,
1636
1637 resolve: resolve,
1638
1639 /**
1640 * Start loading of all queued module dependencies.
1641 *
1642 * @protected
1643 */
1644 work: function () {
1645 var q, batch, implementations, sourceModules;
1646
1647 batch = [];
1648
1649 // Appends a list of modules from the queue to the batch
1650 for ( q = 0; q < queue.length; q++ ) {
1651 // Only load modules which are registered
1652 if ( hasOwn.call( registry, queue[ q ] ) && registry[ queue[ q ] ].state === 'registered' ) {
1653 // Prevent duplicate entries
1654 if ( batch.indexOf( queue[ q ] ) === -1 ) {
1655 batch.push( queue[ q ] );
1656 // Mark registered modules as loading
1657 registry[ queue[ q ] ].state = 'loading';
1658 }
1659 }
1660 }
1661
1662 // Now that the queue has been processed into a batch, clear the queue.
1663 // This MUST happen before we initiate any eval or network request. Otherwise,
1664 // it is possible for a cached script to instantly trigger the same work queue
1665 // again; all before we've cleared it causing each request to include modules
1666 // which are already loaded.
1667 queue = [];
1668
1669 if ( !batch.length ) {
1670 return;
1671 }
1672
1673 mw.loader.store.init();
1674 if ( mw.loader.store.enabled ) {
1675 implementations = [];
1676 sourceModules = [];
1677 batch = batch.filter( function ( module ) {
1678 var implementation = mw.loader.store.get( module );
1679 if ( implementation ) {
1680 implementations.push( implementation );
1681 sourceModules.push( module );
1682 return false;
1683 }
1684 return true;
1685 } );
1686 asyncEval( implementations, function ( err ) {
1687 var failed;
1688 // Not good, the cached mw.loader.implement calls failed! This should
1689 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1690 // Depending on how corrupt the string is, it is likely that some
1691 // modules' implement() succeeded while the ones after the error will
1692 // never run and leave their modules in the 'loading' state forever.
1693 mw.loader.store.stats.failed++;
1694
1695 // Since this is an error not caused by an individual module but by
1696 // something that infected the implement call itself, don't take any
1697 // risks and clear everything in this cache.
1698 mw.loader.store.clear();
1699
1700 mw.trackError( 'resourceloader.exception', {
1701 exception: err,
1702 source: 'store-eval'
1703 } );
1704 // Re-add the failed ones that are still pending back to the batch
1705 failed = sourceModules.filter( function ( module ) {
1706 return registry[ module ].state === 'loading';
1707 } );
1708 batchRequest( failed );
1709 } );
1710 }
1711
1712 batchRequest( batch );
1713 },
1714
1715 /**
1716 * Register a source.
1717 *
1718 * The #work() method will use this information to split up requests by source.
1719 *
1720 * mw.loader.addSource( 'mediawikiwiki', '//www.mediawiki.org/w/load.php' );
1721 *
1722 * @param {string|Object} id Source ID, or object mapping ids to load urls
1723 * @param {string} loadUrl Url to a load.php end point
1724 * @throws {Error} If source id is already registered
1725 */
1726 addSource: function ( id, loadUrl ) {
1727 var source;
1728 // Allow multiple additions
1729 if ( typeof id === 'object' ) {
1730 for ( source in id ) {
1731 mw.loader.addSource( source, id[ source ] );
1732 }
1733 return;
1734 }
1735
1736 if ( hasOwn.call( sources, id ) ) {
1737 throw new Error( 'source already registered: ' + id );
1738 }
1739
1740 sources[ id ] = loadUrl;
1741 },
1742
1743 /**
1744 * Register a module, letting the system know about it and its properties.
1745 *
1746 * The startup modules contain calls to this method.
1747 *
1748 * When using multiple module registration by passing an array, dependencies that
1749 * are specified as references to modules within the array will be resolved before
1750 * the modules are registered.
1751 *
1752 * @param {string|Array} module Module name or array of arrays, each containing
1753 * a list of arguments compatible with this method
1754 * @param {string|number} version Module version hash (falls backs to empty string)
1755 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1756 * @param {string[]} [dependencies] Array of module names on which this module depends.
1757 * @param {string} [group=null] Group which the module is in
1758 * @param {string} [source='local'] Name of the source
1759 * @param {string} [skip=null] Script body of the skip function
1760 */
1761 register: function ( module, version, dependencies, group, source, skip ) {
1762 var i;
1763 // Allow multiple registration
1764 if ( typeof module === 'object' ) {
1765 resolveIndexedDependencies( module );
1766 for ( i = 0; i < module.length; i++ ) {
1767 // module is an array of module names
1768 if ( typeof module[ i ] === 'string' ) {
1769 mw.loader.register( module[ i ] );
1770 // module is an array of arrays
1771 } else if ( typeof module[ i ] === 'object' ) {
1772 mw.loader.register.apply( mw.loader, module[ i ] );
1773 }
1774 }
1775 return;
1776 }
1777 if ( hasOwn.call( registry, module ) ) {
1778 throw new Error( 'module already registered: ' + module );
1779 }
1780 // List the module as registered
1781 registry[ module ] = {
1782 // Exposed to execute() for mw.loader.implement() closures.
1783 // Import happens via require().
1784 module: {
1785 exports: {}
1786 },
1787 version: String( version || '' ),
1788 dependencies: dependencies || [],
1789 group: typeof group === 'string' ? group : null,
1790 source: typeof source === 'string' ? source : 'local',
1791 state: 'registered',
1792 skip: typeof skip === 'string' ? skip : null
1793 };
1794 },
1795
1796 /**
1797 * Implement a module given the components that make up the module.
1798 *
1799 * When #load() or #using() requests one or more modules, the server
1800 * response contain calls to this function.
1801 *
1802 * @param {string} module Name of module and current module version. Formatted
1803 * as '`[name]@[version]`". This version should match the requested version
1804 * (from #batchRequest and #registry). This avoids race conditions (T117587).
1805 * For back-compat with MediaWiki 1.27 and earlier, the version may be omitted.
1806 * @param {Function|Array|string} [script] Function with module code, list of URLs
1807 * to load via `<script src>`, or string of module code for `$.globalEval()`.
1808 * @param {Object} [style] Should follow one of the following patterns:
1809 *
1810 * { "css": [css, ..] }
1811 * { "url": { <media>: [url, ..] } }
1812 *
1813 * And for backwards compatibility (needs to be supported forever due to caching):
1814 *
1815 * { <media>: css }
1816 * { <media>: [url, ..] }
1817 *
1818 * The reason css strings are not concatenated anymore is T33676. We now check
1819 * whether it's safe to extend the stylesheet.
1820 *
1821 * @protected
1822 * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1823 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1824 */
1825 implement: function ( module, script, style, messages, templates ) {
1826 var split = splitModuleKey( module ),
1827 name = split.name,
1828 version = split.version;
1829 // Automatically register module
1830 if ( !hasOwn.call( registry, name ) ) {
1831 mw.loader.register( name );
1832 }
1833 // Check for duplicate implementation
1834 if ( hasOwn.call( registry, name ) && registry[ name ].script !== undefined ) {
1835 throw new Error( 'module already implemented: ' + name );
1836 }
1837 if ( version ) {
1838 // Without this reset, if there is a version mismatch between the
1839 // requested and received module version, then mw.loader.store would
1840 // cache the response under the requested key. Thus poisoning the cache
1841 // indefinitely with a stale value. (T117587)
1842 registry[ name ].version = version;
1843 }
1844 // Attach components
1845 registry[ name ].script = script || null;
1846 registry[ name ].style = style || null;
1847 registry[ name ].messages = messages || null;
1848 registry[ name ].templates = templates || null;
1849 // The module may already have been marked as erroneous
1850 if ( registry[ name ].state !== 'error' && registry[ name ].state !== 'missing' ) {
1851 registry[ name ].state = 'loaded';
1852 if ( allWithImplicitReady( name ) ) {
1853 execute( name );
1854 }
1855 }
1856 },
1857
1858 /**
1859 * Load an external script or one or more modules.
1860 *
1861 * This method takes a list of unrelated modules. Use cases:
1862 *
1863 * - A web page will be composed of many different widgets. These widgets independently
1864 * queue their ResourceLoader modules (`OutputPage::addModules()`). If any of them
1865 * have problems, or are no longer known (e.g. cached HTML), the other modules
1866 * should still be loaded.
1867 * - This method is used for preloading, which must not throw. Later code that
1868 * calls #using() will handle the error.
1869 *
1870 * @param {string|Array} modules Either the name of a module, array of modules,
1871 * or a URL of an external script or style
1872 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
1873 * external script or style; acceptable values are "text/css" and
1874 * "text/javascript"; if no type is provided, text/javascript is assumed.
1875 */
1876 load: function ( modules, type ) {
1877 var filtered, l;
1878
1879 // Allow calling with a url or single dependency as a string
1880 if ( typeof modules === 'string' ) {
1881 // "https://example.org/x.js", "http://example.org/x.js", "//example.org/x.js", "/x.js"
1882 if ( /^(https?:)?\/?\//.test( modules ) ) {
1883 if ( type === 'text/css' ) {
1884 l = document.createElement( 'link' );
1885 l.rel = 'stylesheet';
1886 l.href = modules;
1887 document.head.appendChild( l );
1888 return;
1889 }
1890 if ( type === 'text/javascript' || type === undefined ) {
1891 addScript( modules );
1892 return;
1893 }
1894 // Unknown type
1895 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type );
1896 }
1897 // Called with single module
1898 modules = [ modules ];
1899 }
1900
1901 // Filter out top-level modules that are unknown or failed to load before.
1902 filtered = modules.filter( function ( module ) {
1903 var state = mw.loader.getState( module );
1904 return state !== 'error' && state !== 'missing';
1905 } );
1906 // Resolve remaining list using the known dependency tree.
1907 // This also filters out modules with unknown dependencies. (T36853)
1908 filtered = resolveStubbornly( filtered );
1909 // Some modules are not yet ready, add to module load queue.
1910 enqueue( filtered, undefined, undefined );
1911 },
1912
1913 /**
1914 * Change the state of one or more modules.
1915 *
1916 * @param {Object} modules Object of module name/state pairs
1917 */
1918 state: function ( modules ) {
1919 var module, state;
1920 for ( module in modules ) {
1921 state = modules[ module ];
1922 if ( !hasOwn.call( registry, module ) ) {
1923 mw.loader.register( module );
1924 }
1925 registry[ module ].state = state;
1926 if ( state === 'ready' || state === 'error' || state === 'missing' ) {
1927 // Make sure pending modules depending on this one get executed if their
1928 // dependencies are now fulfilled!
1929 handlePending( module );
1930 }
1931 }
1932 },
1933
1934 /**
1935 * Get the version of a module.
1936 *
1937 * @param {string} module Name of module
1938 * @return {string|null} The version, or null if the module (or its version) is not
1939 * in the registry.
1940 */
1941 getVersion: function ( module ) {
1942 return hasOwn.call( registry, module ) ? registry[ module ].version : null;
1943 },
1944
1945 /**
1946 * Get the state of a module.
1947 *
1948 * @param {string} module Name of module
1949 * @return {string|null} The state, or null if the module (or its state) is not
1950 * in the registry.
1951 */
1952 getState: function ( module ) {
1953 return hasOwn.call( registry, module ) ? registry[ module ].state : null;
1954 },
1955
1956 /**
1957 * Get the names of all registered modules.
1958 *
1959 * @return {Array}
1960 */
1961 getModuleNames: function () {
1962 return Object.keys( registry );
1963 },
1964
1965 /**
1966 * Get the exported value of a module.
1967 *
1968 * This static method is publicly exposed for debugging purposes
1969 * only and must not be used in production code. In production code,
1970 * please use the dynamically provided `require()` function instead.
1971 *
1972 * In case of lazy-loaded modules via mw.loader#using(), the returned
1973 * Promise provides the function, see #using() for examples.
1974 *
1975 * @private
1976 * @since 1.27
1977 * @param {string} moduleName Module name
1978 * @return {Mixed} Exported value
1979 */
1980 require: function ( moduleName ) {
1981 var state = mw.loader.getState( moduleName );
1982
1983 // Only ready modules can be required
1984 if ( state !== 'ready' ) {
1985 // Module may've forgotten to declare a dependency
1986 throw new Error( 'Module "' + moduleName + '" is not loaded.' );
1987 }
1988
1989 return registry[ moduleName ].module.exports;
1990 },
1991
1992 /**
1993 * On browsers that implement the localStorage API, the module store serves as a
1994 * smart complement to the browser cache. Unlike the browser cache, the module store
1995 * can slice a concatenated response from ResourceLoader into its constituent
1996 * modules and cache each of them separately, using each module's versioning scheme
1997 * to determine when the cache should be invalidated.
1998 *
1999 * @private
2000 * @singleton
2001 * @class mw.loader.store
2002 */
2003 store: {
2004 // Whether the store is in use on this page.
2005 enabled: null,
2006
2007 // Modules whose string representation exceeds 100 kB are
2008 // ineligible for storage. See bug T66721.
2009 MODULE_SIZE_MAX: 100 * 1000,
2010
2011 // The contents of the store, mapping '[name]@[version]' keys
2012 // to module implementations.
2013 items: {},
2014
2015 // Cache hit stats
2016 stats: { hits: 0, misses: 0, expired: 0, failed: 0 },
2017
2018 /**
2019 * Construct a JSON-serializable object representing the content of the store.
2020 *
2021 * @return {Object} Module store contents.
2022 */
2023 toJSON: function () {
2024 return { items: mw.loader.store.items, vary: mw.loader.store.getVary() };
2025 },
2026
2027 /**
2028 * Get the localStorage key for the entire module store. The key references
2029 * $wgDBname to prevent clashes between wikis which share a common host.
2030 *
2031 * @return {string} localStorage item key
2032 */
2033 getStoreKey: function () {
2034 return 'MediaWikiModuleStore:' + mw.config.get( 'wgDBname' );
2035 },
2036
2037 /**
2038 * Get a key on which to vary the module cache.
2039 *
2040 * @return {string} String of concatenated vary conditions.
2041 */
2042 getVary: function () {
2043 return mw.config.get( 'skin' ) + ':' +
2044 mw.config.get( 'wgResourceLoaderStorageVersion' ) + ':' +
2045 mw.config.get( 'wgUserLanguage' );
2046 },
2047
2048 /**
2049 * Initialize the store.
2050 *
2051 * Retrieves store from localStorage and (if successfully retrieved) decoding
2052 * the stored JSON value to a plain object.
2053 *
2054 * The try / catch block is used for JSON & localStorage feature detection.
2055 * See the in-line documentation for Modernizr's localStorage feature detection
2056 * code for a full account of why we need a try / catch:
2057 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2058 */
2059 init: function () {
2060 var raw, data;
2061
2062 if ( mw.loader.store.enabled !== null ) {
2063 // Init already ran
2064 return;
2065 }
2066
2067 if (
2068 // Disabled because localStorage quotas are tight and (in Firefox's case)
2069 // shared by multiple origins.
2070 // See T66721, and <https://bugzilla.mozilla.org/show_bug.cgi?id=1064466>.
2071 /Firefox|Opera/.test( navigator.userAgent ) ||
2072
2073 // Disabled by configuration.
2074 !mw.config.get( 'wgResourceLoaderStorageEnabled' )
2075 ) {
2076 // Clear any previous store to free up space. (T66721)
2077 mw.loader.store.clear();
2078 mw.loader.store.enabled = false;
2079 return;
2080 }
2081 if ( mw.config.get( 'debug' ) ) {
2082 // Disable module store in debug mode
2083 mw.loader.store.enabled = false;
2084 return;
2085 }
2086
2087 try {
2088 // This a string we stored, or `null` if the key does not (yet) exist.
2089 raw = localStorage.getItem( mw.loader.store.getStoreKey() );
2090 // If we get here, localStorage is available; mark enabled
2091 mw.loader.store.enabled = true;
2092 // If null, JSON.parse() will cast to string and re-parse, still null.
2093 data = JSON.parse( raw );
2094 if ( data && typeof data.items === 'object' && data.vary === mw.loader.store.getVary() ) {
2095 mw.loader.store.items = data.items;
2096 return;
2097 }
2098 } catch ( e ) {
2099 mw.trackError( 'resourceloader.exception', {
2100 exception: e,
2101 source: 'store-localstorage-init'
2102 } );
2103 }
2104
2105 // If we get here, one of four things happened:
2106 //
2107 // 1. localStorage did not contain our store key.
2108 // This means `raw` is `null`, and we're on a fresh page view (cold cache).
2109 // The store was enabled, and `items` starts fresh.
2110 //
2111 // 2. localStorage contained parseable data under our store key,
2112 // but it's not applicable to our current context (see getVary).
2113 // The store was enabled, and `items` starts fresh.
2114 //
2115 // 3. JSON.parse threw (localStorage contained corrupt data).
2116 // This means `raw` contains a string.
2117 // The store was enabled, and `items` starts fresh.
2118 //
2119 // 4. localStorage threw (disabled or otherwise unavailable).
2120 // This means `raw` was never assigned.
2121 // We will disable the store below.
2122 if ( raw === undefined ) {
2123 // localStorage failed; disable store
2124 mw.loader.store.enabled = false;
2125 }
2126 },
2127
2128 /**
2129 * Retrieve a module from the store and update cache hit stats.
2130 *
2131 * @param {string} module Module name
2132 * @return {string|boolean} Module implementation or false if unavailable
2133 */
2134 get: function ( module ) {
2135 var key;
2136
2137 if ( !mw.loader.store.enabled ) {
2138 return false;
2139 }
2140
2141 key = getModuleKey( module );
2142 if ( key in mw.loader.store.items ) {
2143 mw.loader.store.stats.hits++;
2144 return mw.loader.store.items[ key ];
2145 }
2146 mw.loader.store.stats.misses++;
2147 return false;
2148 },
2149
2150 /**
2151 * Stringify a module and queue it for storage.
2152 *
2153 * @param {string} module Module name
2154 * @param {Object} descriptor The module's descriptor as set in the registry
2155 */
2156 set: function ( module, descriptor ) {
2157 var args, key, src;
2158
2159 if ( !mw.loader.store.enabled ) {
2160 return;
2161 }
2162
2163 key = getModuleKey( module );
2164
2165 if (
2166 // Already stored a copy of this exact version
2167 key in mw.loader.store.items ||
2168 // Module failed to load
2169 descriptor.state !== 'ready' ||
2170 // Unversioned, private, or site-/user-specific
2171 !descriptor.version ||
2172 descriptor.group === 'private' ||
2173 descriptor.group === 'user' ||
2174 // Partial descriptor
2175 // (e.g. skipped module, or style module with state=ready)
2176 [ descriptor.script, descriptor.style, descriptor.messages,
2177 descriptor.templates ].indexOf( undefined ) !== -1
2178 ) {
2179 // Decline to store
2180 return;
2181 }
2182
2183 try {
2184 args = [
2185 JSON.stringify( key ),
2186 typeof descriptor.script === 'function' ?
2187 String( descriptor.script ) :
2188 JSON.stringify( descriptor.script ),
2189 JSON.stringify( descriptor.style ),
2190 JSON.stringify( descriptor.messages ),
2191 JSON.stringify( descriptor.templates )
2192 ];
2193 // Attempted workaround for a possible Opera bug (bug T59567).
2194 // This regex should never match under sane conditions.
2195 if ( /^\s*\(/.test( args[ 1 ] ) ) {
2196 args[ 1 ] = 'function' + args[ 1 ];
2197 mw.trackError( 'resourceloader.assert', { source: 'bug-T59567' } );
2198 }
2199 } catch ( e ) {
2200 mw.trackError( 'resourceloader.exception', {
2201 exception: e,
2202 source: 'store-localstorage-json'
2203 } );
2204 return;
2205 }
2206
2207 src = 'mw.loader.implement(' + args.join( ',' ) + ');';
2208 if ( src.length > mw.loader.store.MODULE_SIZE_MAX ) {
2209 return;
2210 }
2211 mw.loader.store.items[ key ] = src;
2212 mw.loader.store.update();
2213 },
2214
2215 /**
2216 * Iterate through the module store, removing any item that does not correspond
2217 * (in name and version) to an item in the module registry.
2218 */
2219 prune: function () {
2220 var key, module;
2221
2222 for ( key in mw.loader.store.items ) {
2223 module = key.slice( 0, key.indexOf( '@' ) );
2224 if ( getModuleKey( module ) !== key ) {
2225 mw.loader.store.stats.expired++;
2226 delete mw.loader.store.items[ key ];
2227 } else if ( mw.loader.store.items[ key ].length > mw.loader.store.MODULE_SIZE_MAX ) {
2228 // This value predates the enforcement of a size limit on cached modules.
2229 delete mw.loader.store.items[ key ];
2230 }
2231 }
2232 },
2233
2234 /**
2235 * Clear the entire module store right now.
2236 */
2237 clear: function () {
2238 mw.loader.store.items = {};
2239 try {
2240 localStorage.removeItem( mw.loader.store.getStoreKey() );
2241 } catch ( e ) {}
2242 },
2243
2244 /**
2245 * Sync in-memory store back to localStorage.
2246 *
2247 * This function debounces updates. When called with a flush already pending, the
2248 * scheduled flush is postponed. The call to localStorage.setItem will be keep
2249 * being deferred until the page is quiescent for 2 seconds.
2250 *
2251 * Because localStorage is shared by all pages from the same origin, if multiple
2252 * pages are loaded with different module sets, the possibility exists that
2253 * modules saved by one page will be clobbered by another. The only impact of this
2254 * is minor (merely a less efficient cache use) and the problem would be corrected
2255 * by subsequent page views.
2256 *
2257 * @method
2258 */
2259 update: ( function () {
2260 var timer, hasPendingWrites = false;
2261
2262 function flushWrites() {
2263 var data, key;
2264 if ( !mw.loader.store.enabled ) {
2265 return;
2266 }
2267
2268 mw.loader.store.prune();
2269 key = mw.loader.store.getStoreKey();
2270 try {
2271 // Replacing the content of the module store might fail if the new
2272 // contents would exceed the browser's localStorage size limit. To
2273 // avoid clogging the browser with stale data, always remove the old
2274 // value before attempting to set the new one.
2275 localStorage.removeItem( key );
2276 data = JSON.stringify( mw.loader.store );
2277 localStorage.setItem( key, data );
2278 } catch ( e ) {
2279 mw.trackError( 'resourceloader.exception', {
2280 exception: e,
2281 source: 'store-localstorage-update'
2282 } );
2283 }
2284
2285 hasPendingWrites = false;
2286 }
2287
2288 function request() {
2289 // If another mw.loader.store.set()/update() call happens in the narrow
2290 // time window between requestIdleCallback() and flushWrites firing, ignore it.
2291 // It'll be saved by the already-scheduled flush.
2292 if ( !hasPendingWrites ) {
2293 hasPendingWrites = true;
2294 mw.requestIdleCallback( flushWrites );
2295 }
2296 }
2297
2298 return function () {
2299 // Cancel the previous timer (if it hasn't fired yet)
2300 clearTimeout( timer );
2301 timer = setTimeout( request, 2000 );
2302 };
2303 }() )
2304 }
2305 };
2306 }() ),
2307
2308 // Skeleton user object, extended by the 'mediawiki.user' module.
2309 /**
2310 * @class mw.user
2311 * @singleton
2312 */
2313 user: {
2314 /**
2315 * @property {mw.Map}
2316 */
2317 options: new Map(),
2318 /**
2319 * @property {mw.Map}
2320 */
2321 tokens: new Map()
2322 },
2323
2324 // OOUI widgets specific to MediaWiki
2325 widgets: {}
2326
2327 };
2328
2329 // Attach to window and globally alias
2330 window.mw = window.mediaWiki = mw;
2331 }() );