resourceloader: Correct @param doc for mw.loader.state()
[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|string[]} dependencies Module name or array of string module names
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 // Allow calling by single module name
1092 if ( typeof dependencies === 'string' ) {
1093 dependencies = [ dependencies ];
1094 }
1095
1096 if ( allReady( dependencies ) ) {
1097 // Run ready immediately
1098 if ( ready !== undefined ) {
1099 ready();
1100 }
1101
1102 return;
1103 }
1104
1105 if ( anyFailed( dependencies ) ) {
1106 if ( error !== undefined ) {
1107 // Execute error immediately if any dependencies have errors
1108 error(
1109 new Error( 'One or more dependencies failed to load' ),
1110 dependencies
1111 );
1112 }
1113
1114 return;
1115 }
1116
1117 // Not all dependencies are ready, add to the load queue...
1118
1119 // Add ready and error callbacks if they were given
1120 if ( ready !== undefined || error !== undefined ) {
1121 jobs.push( {
1122 // Narrow down the list to modules that are worth waiting for
1123 dependencies: dependencies.filter( function ( module ) {
1124 var state = mw.loader.getState( module );
1125 return state === 'registered' || state === 'loaded' || state === 'loading' || state === 'executing';
1126 } ),
1127 ready: ready,
1128 error: error
1129 } );
1130 }
1131
1132 dependencies.forEach( function ( module ) {
1133 var state = mw.loader.getState( module );
1134 // Only queue modules that are still in the initial 'registered' state
1135 // (not ones already loading, ready or error).
1136 if ( state === 'registered' && queue.indexOf( module ) === -1 ) {
1137 // Private modules must be embedded in the page. Don't bother queuing
1138 // these as the server will deny them anyway (T101806).
1139 if ( registry[ module ].group === 'private' ) {
1140 registry[ module ].state = 'error';
1141 handlePending( module );
1142 return;
1143 }
1144 queue.push( module );
1145 }
1146 } );
1147
1148 mw.loader.work();
1149 }
1150
1151 /**
1152 * Executes a loaded module, making it ready to use
1153 *
1154 * @private
1155 * @param {string} module Module name to execute
1156 */
1157 function execute( module ) {
1158 var key, value, media, i, urls, cssHandle, checkCssHandles, runScript,
1159 cssHandlesRegistered = false;
1160
1161 if ( !hasOwn.call( registry, module ) ) {
1162 throw new Error( 'Module has not been registered yet: ' + module );
1163 }
1164 if ( registry[ module ].state !== 'loaded' ) {
1165 throw new Error( 'Module in state "' + registry[ module ].state + '" may not be executed: ' + module );
1166 }
1167
1168 registry[ module ].state = 'executing';
1169 $CODE.profileExecuteStart();
1170
1171 runScript = function () {
1172 var script, markModuleReady, nestedAddScript;
1173
1174 $CODE.profileScriptStart();
1175 script = registry[ module ].script;
1176 markModuleReady = function () {
1177 $CODE.profileScriptEnd();
1178 registry[ module ].state = 'ready';
1179 handlePending( module );
1180 };
1181 nestedAddScript = function ( arr, callback, i ) {
1182 // Recursively call queueModuleScript() in its own callback
1183 // for each element of arr.
1184 if ( i >= arr.length ) {
1185 // We're at the end of the array
1186 callback();
1187 return;
1188 }
1189
1190 queueModuleScript( arr[ i ], module, function () {
1191 nestedAddScript( arr, callback, i + 1 );
1192 } );
1193 };
1194
1195 try {
1196 if ( Array.isArray( script ) ) {
1197 nestedAddScript( script, markModuleReady, 0 );
1198 } else if ( typeof script === 'function' ) {
1199 // Keep in sync with queueModuleScript() for debug mode
1200 if ( module === 'jquery' ) {
1201 // This is a special case for when 'jquery' itself is being loaded.
1202 // - The standard jquery.js distribution does not set `window.jQuery`
1203 // in CommonJS-compatible environments (Node.js, AMD, RequireJS, etc.).
1204 // - MediaWiki's 'jquery' module also bundles jquery.migrate.js, which
1205 // in a CommonJS-compatible environment, will use require('jquery'),
1206 // but that can't work when we're still inside that module.
1207 script();
1208 } else {
1209 // Pass jQuery twice so that the signature of the closure which wraps
1210 // the script can bind both '$' and 'jQuery'.
1211 script( window.$, window.$, mw.loader.require, registry[ module ].module );
1212 }
1213 markModuleReady();
1214
1215 } else if ( typeof script === 'string' ) {
1216 // Site and user modules are legacy scripts that run in the global scope.
1217 // This is transported as a string instead of a function to avoid needing
1218 // to use string manipulation to undo the function wrapper.
1219 domEval( script );
1220 markModuleReady();
1221
1222 } else {
1223 // Module without script
1224 markModuleReady();
1225 }
1226 } catch ( e ) {
1227 // Use mw.track instead of mw.log because these errors are common in production mode
1228 // (e.g. undefined variable), and mw.log is only enabled in debug mode.
1229 registry[ module ].state = 'error';
1230 $CODE.profileScriptEnd();
1231 mw.trackError( 'resourceloader.exception', {
1232 exception: e, module:
1233 module, source: 'module-execute'
1234 } );
1235 handlePending( module );
1236 }
1237 };
1238
1239 // Add localizations to message system
1240 if ( registry[ module ].messages ) {
1241 mw.messages.set( registry[ module ].messages );
1242 }
1243
1244 // Initialise templates
1245 if ( registry[ module ].templates ) {
1246 mw.templates.set( module, registry[ module ].templates );
1247 }
1248
1249 // Make sure we don't run the scripts until all stylesheet insertions have completed.
1250 ( function () {
1251 var pending = 0;
1252 checkCssHandles = function () {
1253 var ex, dependencies;
1254 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
1255 // one of the cssHandles is fired while we're still creating more handles.
1256 if ( cssHandlesRegistered && pending === 0 && runScript ) {
1257 if ( module === 'user' ) {
1258 // Implicit dependency on the site module. Not real dependency because
1259 // it should run after 'site' regardless of whether it succeeds or fails.
1260 // Note: This is a simplified version of mw.loader.using(), inlined here
1261 // as using() depends on jQuery (T192623).
1262 try {
1263 dependencies = resolve( [ 'site' ] );
1264 } catch ( e ) {
1265 ex = e;
1266 runScript();
1267 }
1268 if ( ex === undefined ) {
1269 enqueue( dependencies, runScript, runScript );
1270 }
1271 } else {
1272 runScript();
1273 }
1274 runScript = undefined; // Revoke
1275 }
1276 };
1277 cssHandle = function () {
1278 var check = checkCssHandles;
1279 pending++;
1280 return function () {
1281 if ( check ) {
1282 pending--;
1283 check();
1284 check = undefined; // Revoke
1285 }
1286 };
1287 };
1288 }() );
1289
1290 // Process styles (see also mw.loader.implement)
1291 // * back-compat: { <media>: css }
1292 // * back-compat: { <media>: [url, ..] }
1293 // * { "css": [css, ..] }
1294 // * { "url": { <media>: [url, ..] } }
1295 if ( registry[ module ].style ) {
1296 for ( key in registry[ module ].style ) {
1297 value = registry[ module ].style[ key ];
1298 media = undefined;
1299
1300 if ( key !== 'url' && key !== 'css' ) {
1301 // Backwards compatibility, key is a media-type
1302 if ( typeof value === 'string' ) {
1303 // back-compat: { <media>: css }
1304 // Ignore 'media' because it isn't supported (nor was it used).
1305 // Strings are pre-wrapped in "@media". The media-type was just ""
1306 // (because it had to be set to something).
1307 // This is one of the reasons why this format is no longer used.
1308 addEmbeddedCSS( value, cssHandle() );
1309 } else {
1310 // back-compat: { <media>: [url, ..] }
1311 media = key;
1312 key = 'bc-url';
1313 }
1314 }
1315
1316 // Array of css strings in key 'css',
1317 // or back-compat array of urls from media-type
1318 if ( Array.isArray( value ) ) {
1319 for ( i = 0; i < value.length; i++ ) {
1320 if ( key === 'bc-url' ) {
1321 // back-compat: { <media>: [url, ..] }
1322 addLink( media, value[ i ] );
1323 } else if ( key === 'css' ) {
1324 // { "css": [css, ..] }
1325 addEmbeddedCSS( value[ i ], cssHandle() );
1326 }
1327 }
1328 // Not an array, but a regular object
1329 // Array of urls inside media-type key
1330 } else if ( typeof value === 'object' ) {
1331 // { "url": { <media>: [url, ..] } }
1332 for ( media in value ) {
1333 urls = value[ media ];
1334 for ( i = 0; i < urls.length; i++ ) {
1335 addLink( media, urls[ i ] );
1336 }
1337 }
1338 }
1339 }
1340 }
1341
1342 // End profiling of execute()-self before we call checkCssHandles(),
1343 // which (sometimes asynchronously) calls runScript(), which we want
1344 // to measure separately without overlap.
1345 $CODE.profileExecuteEnd();
1346
1347 // Kick off.
1348 cssHandlesRegistered = true;
1349 checkCssHandles();
1350 }
1351
1352 function sortQuery( o ) {
1353 var key,
1354 sorted = {},
1355 a = [];
1356
1357 for ( key in o ) {
1358 a.push( key );
1359 }
1360 a.sort();
1361 for ( key = 0; key < a.length; key++ ) {
1362 sorted[ a[ key ] ] = o[ a[ key ] ];
1363 }
1364 return sorted;
1365 }
1366
1367 /**
1368 * Converts a module map of the form `{ foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }`
1369 * to a query string of the form `foo.bar,baz|bar.baz,quux`.
1370 *
1371 * See `ResourceLoader::makePackedModulesString()` in PHP, of which this is a port.
1372 * On the server, unpacking is done by `ResourceLoaderContext::expandModuleNames()`.
1373 *
1374 * Note: This is only half of the logic, the other half has to be in #batchRequest(),
1375 * because its implementation needs to keep track of potential string size in order
1376 * to decide when to split the requests due to url size.
1377 *
1378 * @private
1379 * @param {Object} moduleMap Module map
1380 * @return {Object}
1381 * @return {string} return.str Module query string
1382 * @return {Array} return.list List of module names in matching order
1383 */
1384 function buildModulesString( moduleMap ) {
1385 var p, prefix,
1386 str = [],
1387 list = [];
1388
1389 function restore( suffix ) {
1390 return p + suffix;
1391 }
1392
1393 for ( prefix in moduleMap ) {
1394 p = prefix === '' ? '' : prefix + '.';
1395 str.push( p + moduleMap[ prefix ].join( ',' ) );
1396 list.push.apply( list, moduleMap[ prefix ].map( restore ) );
1397 }
1398 return {
1399 str: str.join( '|' ),
1400 list: list
1401 };
1402 }
1403
1404 /**
1405 * Resolve indexed dependencies.
1406 *
1407 * ResourceLoader uses an optimization to save space which replaces module names in
1408 * dependency lists with the index of that module within the array of module
1409 * registration data if it exists. The benefit is a significant reduction in the data
1410 * size of the startup module. This function changes those dependency lists back to
1411 * arrays of strings.
1412 *
1413 * @private
1414 * @param {Array} modules Modules array
1415 */
1416 function resolveIndexedDependencies( modules ) {
1417 var i, j, deps;
1418 function resolveIndex( dep ) {
1419 return typeof dep === 'number' ? modules[ dep ][ 0 ] : dep;
1420 }
1421 for ( i = 0; i < modules.length; i++ ) {
1422 deps = modules[ i ][ 2 ];
1423 if ( deps ) {
1424 for ( j = 0; j < deps.length; j++ ) {
1425 deps[ j ] = resolveIndex( deps[ j ] );
1426 }
1427 }
1428 }
1429 }
1430
1431 /**
1432 * @private
1433 * @param {Object} params Map of parameter names to values
1434 * @return {string}
1435 */
1436 function makeQueryString( params ) {
1437 return Object.keys( params ).map( function ( key ) {
1438 return encodeURIComponent( key ) + '=' + encodeURIComponent( params[ key ] );
1439 } ).join( '&' );
1440 }
1441
1442 /**
1443 * Create network requests for a batch of modules.
1444 *
1445 * This is an internal method for #work(). This must not be called directly
1446 * unless the modules are already registered, and no request is in progress,
1447 * and the module state has already been set to `loading`.
1448 *
1449 * @private
1450 * @param {string[]} batch
1451 */
1452 function batchRequest( batch ) {
1453 var reqBase, splits, maxQueryLength, b, bSource, bGroup, bSourceGroup,
1454 source, group, i, modules, sourceLoadScript,
1455 currReqBase, currReqBaseLength, moduleMap, currReqModules, l,
1456 lastDotIndex, prefix, suffix, bytesAdded;
1457
1458 /**
1459 * Start the currently drafted request to the server.
1460 *
1461 * @ignore
1462 */
1463 function doRequest() {
1464 // Optimisation: Inherit (Object.create), not copy ($.extend)
1465 var query = Object.create( currReqBase ),
1466 packed = buildModulesString( moduleMap );
1467 query.modules = packed.str;
1468 // The packing logic can change the effective order, even if the input was
1469 // sorted. As such, the call to getCombinedVersion() must use this
1470 // effective order, instead of currReqModules, as otherwise the combined
1471 // version will not match the hash expected by the server based on
1472 // combining versions from the module query string in-order. (T188076)
1473 query.version = getCombinedVersion( packed.list );
1474 query = sortQuery( query );
1475 addScript( sourceLoadScript + '?' + makeQueryString( query ) );
1476 }
1477
1478 if ( !batch.length ) {
1479 return;
1480 }
1481
1482 // Always order modules alphabetically to help reduce cache
1483 // misses for otherwise identical content.
1484 batch.sort();
1485
1486 // Query parameters common to all requests
1487 reqBase = {
1488 skin: mw.config.get( 'skin' ),
1489 lang: mw.config.get( 'wgUserLanguage' ),
1490 debug: mw.config.get( 'debug' )
1491 };
1492 maxQueryLength = mw.config.get( 'wgResourceLoaderMaxQueryLength', 2000 );
1493
1494 // Split module list by source and by group.
1495 splits = {};
1496 for ( b = 0; b < batch.length; b++ ) {
1497 bSource = registry[ batch[ b ] ].source;
1498 bGroup = registry[ batch[ b ] ].group;
1499 if ( !hasOwn.call( splits, bSource ) ) {
1500 splits[ bSource ] = {};
1501 }
1502 if ( !hasOwn.call( splits[ bSource ], bGroup ) ) {
1503 splits[ bSource ][ bGroup ] = [];
1504 }
1505 bSourceGroup = splits[ bSource ][ bGroup ];
1506 bSourceGroup.push( batch[ b ] );
1507 }
1508
1509 for ( source in splits ) {
1510
1511 sourceLoadScript = sources[ source ];
1512
1513 for ( group in splits[ source ] ) {
1514
1515 // Cache access to currently selected list of
1516 // modules for this group from this source.
1517 modules = splits[ source ][ group ];
1518
1519 // Query parameters common to requests for this module group
1520 // Optimisation: Inherit (Object.create), not copy ($.extend)
1521 currReqBase = Object.create( reqBase );
1522 // User modules require a user name in the query string.
1523 if ( group === 'user' && mw.config.get( 'wgUserName' ) !== null ) {
1524 currReqBase.user = mw.config.get( 'wgUserName' );
1525 }
1526
1527 // In addition to currReqBase, doRequest() will also add 'modules' and 'version'.
1528 // > '&modules='.length === 9
1529 // > '&version=1234567'.length === 16
1530 // > 9 + 16 = 25
1531 currReqBaseLength = makeQueryString( currReqBase ).length + 25;
1532
1533 // We may need to split up the request to honor the query string length limit,
1534 // so build it piece by piece.
1535 l = currReqBaseLength;
1536 moduleMap = {}; // { prefix: [ suffixes ] }
1537 currReqModules = [];
1538
1539 for ( i = 0; i < modules.length; i++ ) {
1540 // Determine how many bytes this module would add to the query string
1541 lastDotIndex = modules[ i ].lastIndexOf( '.' );
1542 // If lastDotIndex is -1, substr() returns an empty string
1543 prefix = modules[ i ].substr( 0, lastDotIndex );
1544 suffix = modules[ i ].slice( lastDotIndex + 1 );
1545 bytesAdded = hasOwn.call( moduleMap, prefix ) ?
1546 suffix.length + 3 : // '%2C'.length == 3
1547 modules[ i ].length + 3; // '%7C'.length == 3
1548
1549 // If the url would become too long, create a new one, but don't create empty requests
1550 if ( maxQueryLength > 0 && currReqModules.length && l + bytesAdded > maxQueryLength ) {
1551 // Dispatch what we've got...
1552 doRequest();
1553 // .. and start again.
1554 l = currReqBaseLength;
1555 moduleMap = {};
1556 currReqModules = [];
1557
1558 mw.track( 'resourceloader.splitRequest', { maxQueryLength: maxQueryLength } );
1559 }
1560 if ( !hasOwn.call( moduleMap, prefix ) ) {
1561 moduleMap[ prefix ] = [];
1562 }
1563 l += bytesAdded;
1564 moduleMap[ prefix ].push( suffix );
1565 currReqModules.push( modules[ i ] );
1566 }
1567 // If there's anything left in moduleMap, request that too
1568 if ( currReqModules.length ) {
1569 doRequest();
1570 }
1571 }
1572 }
1573 }
1574
1575 /**
1576 * @private
1577 * @param {string[]} implementations Array containing pieces of JavaScript code in the
1578 * form of calls to mw.loader#implement().
1579 * @param {Function} cb Callback in case of failure
1580 * @param {Error} cb.err
1581 */
1582 function asyncEval( implementations, cb ) {
1583 if ( !implementations.length ) {
1584 return;
1585 }
1586 mw.requestIdleCallback( function () {
1587 try {
1588 domEval( implementations.join( ';' ) );
1589 } catch ( err ) {
1590 cb( err );
1591 }
1592 } );
1593 }
1594
1595 /**
1596 * Make a versioned key for a specific module.
1597 *
1598 * @private
1599 * @param {string} module Module name
1600 * @return {string|null} Module key in format '`[name]@[version]`',
1601 * or null if the module does not exist
1602 */
1603 function getModuleKey( module ) {
1604 return hasOwn.call( registry, module ) ?
1605 ( module + '@' + registry[ module ].version ) : null;
1606 }
1607
1608 /**
1609 * @private
1610 * @param {string} key Module name or '`[name]@[version]`'
1611 * @return {Object}
1612 */
1613 function splitModuleKey( key ) {
1614 var index = key.indexOf( '@' );
1615 if ( index === -1 ) {
1616 return {
1617 name: key,
1618 version: ''
1619 };
1620 }
1621 return {
1622 name: key.slice( 0, index ),
1623 version: key.slice( index + 1 )
1624 };
1625 }
1626
1627 /* Public Members */
1628 return {
1629 /**
1630 * The module registry is exposed as an aid for debugging and inspecting page
1631 * state; it is not a public interface for modifying the registry.
1632 *
1633 * @see #registry
1634 * @property
1635 * @private
1636 */
1637 moduleRegistry: registry,
1638
1639 /**
1640 * @inheritdoc #newStyleTag
1641 * @method
1642 */
1643 addStyleTag: newStyleTag,
1644
1645 enqueue: enqueue,
1646
1647 resolve: resolve,
1648
1649 /**
1650 * Start loading of all queued module dependencies.
1651 *
1652 * @protected
1653 */
1654 work: function () {
1655 var q, batch, implementations, sourceModules;
1656
1657 batch = [];
1658
1659 // Appends a list of modules from the queue to the batch
1660 for ( q = 0; q < queue.length; q++ ) {
1661 // Only load modules which are registered
1662 if ( hasOwn.call( registry, queue[ q ] ) && registry[ queue[ q ] ].state === 'registered' ) {
1663 // Prevent duplicate entries
1664 if ( batch.indexOf( queue[ q ] ) === -1 ) {
1665 batch.push( queue[ q ] );
1666 // Mark registered modules as loading
1667 registry[ queue[ q ] ].state = 'loading';
1668 }
1669 }
1670 }
1671
1672 // Now that the queue has been processed into a batch, clear the queue.
1673 // This MUST happen before we initiate any eval or network request. Otherwise,
1674 // it is possible for a cached script to instantly trigger the same work queue
1675 // again; all before we've cleared it causing each request to include modules
1676 // which are already loaded.
1677 queue = [];
1678
1679 if ( !batch.length ) {
1680 return;
1681 }
1682
1683 mw.loader.store.init();
1684 if ( mw.loader.store.enabled ) {
1685 implementations = [];
1686 sourceModules = [];
1687 batch = batch.filter( function ( module ) {
1688 var implementation = mw.loader.store.get( module );
1689 if ( implementation ) {
1690 implementations.push( implementation );
1691 sourceModules.push( module );
1692 return false;
1693 }
1694 return true;
1695 } );
1696 asyncEval( implementations, function ( err ) {
1697 var failed;
1698 // Not good, the cached mw.loader.implement calls failed! This should
1699 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1700 // Depending on how corrupt the string is, it is likely that some
1701 // modules' implement() succeeded while the ones after the error will
1702 // never run and leave their modules in the 'loading' state forever.
1703 mw.loader.store.stats.failed++;
1704
1705 // Since this is an error not caused by an individual module but by
1706 // something that infected the implement call itself, don't take any
1707 // risks and clear everything in this cache.
1708 mw.loader.store.clear();
1709
1710 mw.trackError( 'resourceloader.exception', {
1711 exception: err,
1712 source: 'store-eval'
1713 } );
1714 // Re-add the failed ones that are still pending back to the batch
1715 failed = sourceModules.filter( function ( module ) {
1716 return registry[ module ].state === 'loading';
1717 } );
1718 batchRequest( failed );
1719 } );
1720 }
1721
1722 batchRequest( batch );
1723 },
1724
1725 /**
1726 * Register a source.
1727 *
1728 * The #work() method will use this information to split up requests by source.
1729 *
1730 * mw.loader.addSource( 'mediawikiwiki', '//www.mediawiki.org/w/load.php' );
1731 *
1732 * @param {string|Object} id Source ID, or object mapping ids to load urls
1733 * @param {string} loadUrl Url to a load.php end point
1734 * @throws {Error} If source id is already registered
1735 */
1736 addSource: function ( id, loadUrl ) {
1737 var source;
1738 // Allow multiple additions
1739 if ( typeof id === 'object' ) {
1740 for ( source in id ) {
1741 mw.loader.addSource( source, id[ source ] );
1742 }
1743 return;
1744 }
1745
1746 if ( hasOwn.call( sources, id ) ) {
1747 throw new Error( 'source already registered: ' + id );
1748 }
1749
1750 sources[ id ] = loadUrl;
1751 },
1752
1753 /**
1754 * Register a module, letting the system know about it and its properties.
1755 *
1756 * The startup modules contain calls to this method.
1757 *
1758 * When using multiple module registration by passing an array, dependencies that
1759 * are specified as references to modules within the array will be resolved before
1760 * the modules are registered.
1761 *
1762 * @param {string|Array} module Module name or array of arrays, each containing
1763 * a list of arguments compatible with this method
1764 * @param {string|number} version Module version hash (falls backs to empty string)
1765 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1766 * @param {string|Array} dependencies One string or array of strings of module
1767 * names on which this module depends.
1768 * @param {string} [group=null] Group which the module is in
1769 * @param {string} [source='local'] Name of the source
1770 * @param {string} [skip=null] Script body of the skip function
1771 */
1772 register: function ( module, version, dependencies, group, source, skip ) {
1773 var i, deps;
1774 // Allow multiple registration
1775 if ( typeof module === 'object' ) {
1776 resolveIndexedDependencies( module );
1777 for ( i = 0; i < module.length; i++ ) {
1778 // module is an array of module names
1779 if ( typeof module[ i ] === 'string' ) {
1780 mw.loader.register( module[ i ] );
1781 // module is an array of arrays
1782 } else if ( typeof module[ i ] === 'object' ) {
1783 mw.loader.register.apply( mw.loader, module[ i ] );
1784 }
1785 }
1786 return;
1787 }
1788 if ( hasOwn.call( registry, module ) ) {
1789 throw new Error( 'module already registered: ' + module );
1790 }
1791 if ( typeof dependencies === 'string' ) {
1792 // A single module name
1793 deps = [ dependencies ];
1794 } else if ( typeof dependencies === 'object' ) {
1795 // Array of module names
1796 deps = dependencies;
1797 }
1798 // List the module as registered
1799 registry[ module ] = {
1800 // Exposed to execute() for mw.loader.implement() closures.
1801 // Import happens via require().
1802 module: {
1803 exports: {}
1804 },
1805 version: version !== undefined ? String( version ) : '',
1806 dependencies: deps || [],
1807 group: typeof group === 'string' ? group : null,
1808 source: typeof source === 'string' ? source : 'local',
1809 state: 'registered',
1810 skip: typeof skip === 'string' ? skip : null
1811 };
1812 },
1813
1814 /**
1815 * Implement a module given the components that make up the module.
1816 *
1817 * When #load() or #using() requests one or more modules, the server
1818 * response contain calls to this function.
1819 *
1820 * @param {string} module Name of module and current module version. Formatted
1821 * as '`[name]@[version]`". This version should match the requested version
1822 * (from #batchRequest and #registry). This avoids race conditions (T117587).
1823 * For back-compat with MediaWiki 1.27 and earlier, the version may be omitted.
1824 * @param {Function|Array|string} [script] Function with module code, list of URLs
1825 * to load via `<script src>`, or string of module code for `$.globalEval()`.
1826 * @param {Object} [style] Should follow one of the following patterns:
1827 *
1828 * { "css": [css, ..] }
1829 * { "url": { <media>: [url, ..] } }
1830 *
1831 * And for backwards compatibility (needs to be supported forever due to caching):
1832 *
1833 * { <media>: css }
1834 * { <media>: [url, ..] }
1835 *
1836 * The reason css strings are not concatenated anymore is T33676. We now check
1837 * whether it's safe to extend the stylesheet.
1838 *
1839 * @protected
1840 * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1841 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1842 */
1843 implement: function ( module, script, style, messages, templates ) {
1844 var split = splitModuleKey( module ),
1845 name = split.name,
1846 version = split.version;
1847 // Automatically register module
1848 if ( !hasOwn.call( registry, name ) ) {
1849 mw.loader.register( name );
1850 }
1851 // Check for duplicate implementation
1852 if ( hasOwn.call( registry, name ) && registry[ name ].script !== undefined ) {
1853 throw new Error( 'module already implemented: ' + name );
1854 }
1855 if ( version ) {
1856 // Without this reset, if there is a version mismatch between the
1857 // requested and received module version, then mw.loader.store would
1858 // cache the response under the requested key. Thus poisoning the cache
1859 // indefinitely with a stale value. (T117587)
1860 registry[ name ].version = version;
1861 }
1862 // Attach components
1863 registry[ name ].script = script || null;
1864 registry[ name ].style = style || null;
1865 registry[ name ].messages = messages || null;
1866 registry[ name ].templates = templates || null;
1867 // The module may already have been marked as erroneous
1868 if ( registry[ name ].state !== 'error' && registry[ name ].state !== 'missing' ) {
1869 registry[ name ].state = 'loaded';
1870 if ( allWithImplicitReady( name ) ) {
1871 execute( name );
1872 }
1873 }
1874 },
1875
1876 /**
1877 * Load an external script or one or more modules.
1878 *
1879 * This method takes a list of unrelated modules. Use cases:
1880 *
1881 * - A web page will be composed of many different widgets. These widgets independently
1882 * queue their ResourceLoader modules (`OutputPage::addModules()`). If any of them
1883 * have problems, or are no longer known (e.g. cached HTML), the other modules
1884 * should still be loaded.
1885 * - This method is used for preloading, which must not throw. Later code that
1886 * calls #using() will handle the error.
1887 *
1888 * @param {string|Array} modules Either the name of a module, array of modules,
1889 * or a URL of an external script or style
1890 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
1891 * external script or style; acceptable values are "text/css" and
1892 * "text/javascript"; if no type is provided, text/javascript is assumed.
1893 */
1894 load: function ( modules, type ) {
1895 var filtered, l;
1896
1897 // Allow calling with a url or single dependency as a string
1898 if ( typeof modules === 'string' ) {
1899 // "https://example.org/x.js", "http://example.org/x.js", "//example.org/x.js", "/x.js"
1900 if ( /^(https?:)?\/?\//.test( modules ) ) {
1901 if ( type === 'text/css' ) {
1902 l = document.createElement( 'link' );
1903 l.rel = 'stylesheet';
1904 l.href = modules;
1905 document.head.appendChild( l );
1906 return;
1907 }
1908 if ( type === 'text/javascript' || type === undefined ) {
1909 addScript( modules );
1910 return;
1911 }
1912 // Unknown type
1913 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type );
1914 }
1915 // Called with single module
1916 modules = [ modules ];
1917 }
1918
1919 // Filter out top-level modules that are unknown or failed to load before.
1920 filtered = modules.filter( function ( module ) {
1921 var state = mw.loader.getState( module );
1922 return state !== 'error' && state !== 'missing';
1923 } );
1924 // Resolve remaining list using the known dependency tree.
1925 // This also filters out modules with unknown dependencies. (T36853)
1926 filtered = resolveStubbornly( filtered );
1927 // Some modules are not yet ready, add to module load queue.
1928 enqueue( filtered, undefined, undefined );
1929 },
1930
1931 /**
1932 * Change the state of one or more modules.
1933 *
1934 * @param {Object} modules Object of module name/state pairs
1935 */
1936 state: function ( modules ) {
1937 var module, state;
1938 for ( module in modules ) {
1939 state = modules[ module ];
1940 if ( !hasOwn.call( registry, module ) ) {
1941 mw.loader.register( module );
1942 }
1943 registry[ module ].state = state;
1944 if ( state === 'ready' || state === 'error' || state === 'missing' ) {
1945 // Make sure pending modules depending on this one get executed if their
1946 // dependencies are now fulfilled!
1947 handlePending( module );
1948 }
1949 }
1950 },
1951
1952 /**
1953 * Get the version of a module.
1954 *
1955 * @param {string} module Name of module
1956 * @return {string|null} The version, or null if the module (or its version) is not
1957 * in the registry.
1958 */
1959 getVersion: function ( module ) {
1960 return hasOwn.call( registry, module ) ? registry[ module ].version : null;
1961 },
1962
1963 /**
1964 * Get the state of a module.
1965 *
1966 * @param {string} module Name of module
1967 * @return {string|null} The state, or null if the module (or its state) is not
1968 * in the registry.
1969 */
1970 getState: function ( module ) {
1971 return hasOwn.call( registry, module ) ? registry[ module ].state : null;
1972 },
1973
1974 /**
1975 * Get the names of all registered modules.
1976 *
1977 * @return {Array}
1978 */
1979 getModuleNames: function () {
1980 return Object.keys( registry );
1981 },
1982
1983 /**
1984 * Get the exported value of a module.
1985 *
1986 * This static method is publicly exposed for debugging purposes
1987 * only and must not be used in production code. In production code,
1988 * please use the dynamically provided `require()` function instead.
1989 *
1990 * In case of lazy-loaded modules via mw.loader#using(), the returned
1991 * Promise provides the function, see #using() for examples.
1992 *
1993 * @private
1994 * @since 1.27
1995 * @param {string} moduleName Module name
1996 * @return {Mixed} Exported value
1997 */
1998 require: function ( moduleName ) {
1999 var state = mw.loader.getState( moduleName );
2000
2001 // Only ready modules can be required
2002 if ( state !== 'ready' ) {
2003 // Module may've forgotten to declare a dependency
2004 throw new Error( 'Module "' + moduleName + '" is not loaded.' );
2005 }
2006
2007 return registry[ moduleName ].module.exports;
2008 },
2009
2010 /**
2011 * On browsers that implement the localStorage API, the module store serves as a
2012 * smart complement to the browser cache. Unlike the browser cache, the module store
2013 * can slice a concatenated response from ResourceLoader into its constituent
2014 * modules and cache each of them separately, using each module's versioning scheme
2015 * to determine when the cache should be invalidated.
2016 *
2017 * @singleton
2018 * @class mw.loader.store
2019 */
2020 store: {
2021 // Whether the store is in use on this page.
2022 enabled: null,
2023
2024 // Modules whose string representation exceeds 100 kB are
2025 // ineligible for storage. See bug T66721.
2026 MODULE_SIZE_MAX: 100 * 1000,
2027
2028 // The contents of the store, mapping '[name]@[version]' keys
2029 // to module implementations.
2030 items: {},
2031
2032 // Cache hit stats
2033 stats: { hits: 0, misses: 0, expired: 0, failed: 0 },
2034
2035 /**
2036 * Construct a JSON-serializable object representing the content of the store.
2037 *
2038 * @return {Object} Module store contents.
2039 */
2040 toJSON: function () {
2041 return { items: mw.loader.store.items, vary: mw.loader.store.getVary() };
2042 },
2043
2044 /**
2045 * Get the localStorage key for the entire module store. The key references
2046 * $wgDBname to prevent clashes between wikis which share a common host.
2047 *
2048 * @return {string} localStorage item key
2049 */
2050 getStoreKey: function () {
2051 return 'MediaWikiModuleStore:' + mw.config.get( 'wgDBname' );
2052 },
2053
2054 /**
2055 * Get a key on which to vary the module cache.
2056 *
2057 * @return {string} String of concatenated vary conditions.
2058 */
2059 getVary: function () {
2060 return [
2061 mw.config.get( 'skin' ),
2062 mw.config.get( 'wgResourceLoaderStorageVersion' ),
2063 mw.config.get( 'wgUserLanguage' )
2064 ].join( ':' );
2065 },
2066
2067 /**
2068 * Initialize the store.
2069 *
2070 * Retrieves store from localStorage and (if successfully retrieved) decoding
2071 * the stored JSON value to a plain object.
2072 *
2073 * The try / catch block is used for JSON & localStorage feature detection.
2074 * See the in-line documentation for Modernizr's localStorage feature detection
2075 * code for a full account of why we need a try / catch:
2076 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2077 */
2078 init: function () {
2079 var raw, data;
2080
2081 if ( mw.loader.store.enabled !== null ) {
2082 // Init already ran
2083 return;
2084 }
2085
2086 if (
2087 // Disabled because localStorage quotas are tight and (in Firefox's case)
2088 // shared by multiple origins.
2089 // See T66721, and <https://bugzilla.mozilla.org/show_bug.cgi?id=1064466>.
2090 /Firefox|Opera/.test( navigator.userAgent ) ||
2091
2092 // Disabled by configuration.
2093 !mw.config.get( 'wgResourceLoaderStorageEnabled' )
2094 ) {
2095 // Clear any previous store to free up space. (T66721)
2096 mw.loader.store.clear();
2097 mw.loader.store.enabled = false;
2098 return;
2099 }
2100 if ( mw.config.get( 'debug' ) ) {
2101 // Disable module store in debug mode
2102 mw.loader.store.enabled = false;
2103 return;
2104 }
2105
2106 try {
2107 raw = localStorage.getItem( mw.loader.store.getStoreKey() );
2108 // If we get here, localStorage is available; mark enabled
2109 mw.loader.store.enabled = true;
2110 data = JSON.parse( raw );
2111 if ( data && typeof data.items === 'object' && data.vary === mw.loader.store.getVary() ) {
2112 mw.loader.store.items = data.items;
2113 return;
2114 }
2115 } catch ( e ) {
2116 mw.trackError( 'resourceloader.exception', {
2117 exception: e,
2118 source: 'store-localstorage-init'
2119 } );
2120 }
2121
2122 if ( raw === undefined ) {
2123 // localStorage failed; disable store
2124 mw.loader.store.enabled = false;
2125 } else {
2126 mw.loader.store.update();
2127 }
2128 },
2129
2130 /**
2131 * Retrieve a module from the store and update cache hit stats.
2132 *
2133 * @param {string} module Module name
2134 * @return {string|boolean} Module implementation or false if unavailable
2135 */
2136 get: function ( module ) {
2137 var key;
2138
2139 if ( !mw.loader.store.enabled ) {
2140 return false;
2141 }
2142
2143 key = getModuleKey( module );
2144 if ( key in mw.loader.store.items ) {
2145 mw.loader.store.stats.hits++;
2146 return mw.loader.store.items[ key ];
2147 }
2148 mw.loader.store.stats.misses++;
2149 return false;
2150 },
2151
2152 /**
2153 * Stringify a module and queue it for storage.
2154 *
2155 * @param {string} module Module name
2156 * @param {Object} descriptor The module's descriptor as set in the registry
2157 * @return {boolean} Module was set
2158 */
2159 set: function ( module, descriptor ) {
2160 var args, key, src;
2161
2162 if ( !mw.loader.store.enabled ) {
2163 return false;
2164 }
2165
2166 key = getModuleKey( module );
2167
2168 if (
2169 // Already stored a copy of this exact version
2170 key in mw.loader.store.items ||
2171 // Module failed to load
2172 descriptor.state !== 'ready' ||
2173 // Unversioned, private, or site-/user-specific
2174 !descriptor.version ||
2175 descriptor.group === 'private' ||
2176 descriptor.group === 'user' ||
2177 // Partial descriptor
2178 // (e.g. skipped module, or style module with state=ready)
2179 [ descriptor.script, descriptor.style, descriptor.messages,
2180 descriptor.templates ].indexOf( undefined ) !== -1
2181 ) {
2182 // Decline to store
2183 return false;
2184 }
2185
2186 try {
2187 args = [
2188 JSON.stringify( key ),
2189 typeof descriptor.script === 'function' ?
2190 String( descriptor.script ) :
2191 JSON.stringify( descriptor.script ),
2192 JSON.stringify( descriptor.style ),
2193 JSON.stringify( descriptor.messages ),
2194 JSON.stringify( descriptor.templates )
2195 ];
2196 // Attempted workaround for a possible Opera bug (bug T59567).
2197 // This regex should never match under sane conditions.
2198 if ( /^\s*\(/.test( args[ 1 ] ) ) {
2199 args[ 1 ] = 'function' + args[ 1 ];
2200 mw.trackError( 'resourceloader.assert', { source: 'bug-T59567' } );
2201 }
2202 } catch ( e ) {
2203 mw.trackError( 'resourceloader.exception', {
2204 exception: e,
2205 source: 'store-localstorage-json'
2206 } );
2207 return false;
2208 }
2209
2210 src = 'mw.loader.implement(' + args.join( ',' ) + ');';
2211 if ( src.length > mw.loader.store.MODULE_SIZE_MAX ) {
2212 return false;
2213 }
2214 mw.loader.store.items[ key ] = src;
2215 mw.loader.store.update();
2216 return true;
2217 },
2218
2219 /**
2220 * Iterate through the module store, removing any item that does not correspond
2221 * (in name and version) to an item in the module registry.
2222 *
2223 * @return {boolean} Store was pruned
2224 */
2225 prune: function () {
2226 var key, module;
2227
2228 if ( !mw.loader.store.enabled ) {
2229 return false;
2230 }
2231
2232 for ( key in mw.loader.store.items ) {
2233 module = key.slice( 0, key.indexOf( '@' ) );
2234 if ( getModuleKey( module ) !== key ) {
2235 mw.loader.store.stats.expired++;
2236 delete mw.loader.store.items[ key ];
2237 } else if ( mw.loader.store.items[ key ].length > mw.loader.store.MODULE_SIZE_MAX ) {
2238 // This value predates the enforcement of a size limit on cached modules.
2239 delete mw.loader.store.items[ key ];
2240 }
2241 }
2242 return true;
2243 },
2244
2245 /**
2246 * Clear the entire module store right now.
2247 */
2248 clear: function () {
2249 mw.loader.store.items = {};
2250 try {
2251 localStorage.removeItem( mw.loader.store.getStoreKey() );
2252 } catch ( ignored ) {}
2253 },
2254
2255 /**
2256 * Sync in-memory store back to localStorage.
2257 *
2258 * This function debounces updates. When called with a flush already pending,
2259 * the call is coalesced into the pending update. The call to
2260 * localStorage.setItem will be naturally deferred until the page is quiescent.
2261 *
2262 * Because localStorage is shared by all pages from the same origin, if multiple
2263 * pages are loaded with different module sets, the possibility exists that
2264 * modules saved by one page will be clobbered by another. But the impact would
2265 * be minor and the problem would be corrected by subsequent page views.
2266 *
2267 * @method
2268 */
2269 update: ( function () {
2270 var hasPendingWrite = false;
2271
2272 function flushWrites() {
2273 var data, key;
2274 if ( !hasPendingWrite || !mw.loader.store.enabled ) {
2275 return;
2276 }
2277
2278 mw.loader.store.prune();
2279 key = mw.loader.store.getStoreKey();
2280 try {
2281 // Replacing the content of the module store might fail if the new
2282 // contents would exceed the browser's localStorage size limit. To
2283 // avoid clogging the browser with stale data, always remove the old
2284 // value before attempting to set the new one.
2285 localStorage.removeItem( key );
2286 data = JSON.stringify( mw.loader.store );
2287 localStorage.setItem( key, data );
2288 } catch ( e ) {
2289 mw.trackError( 'resourceloader.exception', {
2290 exception: e,
2291 source: 'store-localstorage-update'
2292 } );
2293 }
2294
2295 hasPendingWrite = false;
2296 }
2297
2298 return function () {
2299 if ( !hasPendingWrite ) {
2300 hasPendingWrite = true;
2301 mw.requestIdleCallback( flushWrites );
2302 }
2303 };
2304 }() )
2305 }
2306 };
2307 }() ),
2308
2309 // Skeleton user object, extended by the 'mediawiki.user' module.
2310 /**
2311 * @class mw.user
2312 * @singleton
2313 */
2314 user: {
2315 /**
2316 * @property {mw.Map}
2317 */
2318 options: new Map(),
2319 /**
2320 * @property {mw.Map}
2321 */
2322 tokens: new Map()
2323 },
2324
2325 // OOUI widgets specific to MediaWiki
2326 widgets: {}
2327
2328 };
2329
2330 // Attach to window and globally alias
2331 window.mw = window.mediaWiki = mw;
2332 }() );