Merge "maintenance: Implement 'file' type and use for jquery and qunitjs"
[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 = Object.create( null );
59 }
60 StringSet.prototype.add = function ( value ) {
61 this.set[ value ] = true;
62 };
63 StringSet.prototype.has = function ( value ) {
64 return value in this.set;
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 = Object.create( null );
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 ] ] = selection[ i ] in this.values ?
189 this.values[ selection[ i ] ] :
190 fallback;
191 }
192 }
193 return results;
194 }
195
196 if ( typeof selection === 'string' ) {
197 return selection in this.values ?
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' || !( selection[ i ] in this.values ) ) {
251 return false;
252 }
253 }
254 return true;
255 }
256 return typeof selection === 'string' && selection in this.values;
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 nextCssBuffer,
638 rAF = window.requestAnimationFrame || setTimeout;
639
640 /**
641 * Create a new style element and add it to the DOM.
642 *
643 * @private
644 * @param {string} text CSS text
645 * @param {Node|null} [nextNode] The element where the style tag
646 * should be inserted before
647 * @return {HTMLElement} Reference to the created style element
648 */
649 function newStyleTag( text, nextNode ) {
650 var el = document.createElement( 'style' );
651 el.appendChild( document.createTextNode( text ) );
652 if ( nextNode && nextNode.parentNode ) {
653 nextNode.parentNode.insertBefore( el, nextNode );
654 } else {
655 document.head.appendChild( el );
656 }
657 return el;
658 }
659
660 /**
661 * @private
662 * @param {Object} cssBuffer
663 */
664 function flushCssBuffer( cssBuffer ) {
665 var i;
666 // Mark this object as inactive now so that further calls to addEmbeddedCSS() from
667 // the callbacks go to a new buffer instead of this one (T105973)
668 cssBuffer.active = false;
669 newStyleTag( cssBuffer.cssText, marker );
670 for ( i = 0; i < cssBuffer.callbacks.length; i++ ) {
671 cssBuffer.callbacks[ i ]();
672 }
673 }
674
675 /**
676 * Add a bit of CSS text to the current browser page.
677 *
678 * The creation and insertion of the `<style>` element is debounced for two reasons:
679 *
680 * - Performing the insertion before the next paint round via requestAnimationFrame
681 * avoids forced or wasted style recomputations, which are expensive in browsers.
682 * - Reduce how often new stylesheets are inserted by letting additional calls to this
683 * function accumulate into a buffer for at least one JavaScript tick. Modules are
684 * received from the server in batches, which means there is likely going to be many
685 * calls to this function in a row within the same tick / the same call stack.
686 * See also T47810.
687 *
688 * @private
689 * @param {string} cssText CSS text to be added in a `<style>` tag.
690 * @param {Function} callback Called after the insertion has occurred
691 */
692 function addEmbeddedCSS( cssText, callback ) {
693 // Create a buffer if:
694 // - We don't have one yet.
695 // - The previous one is closed.
696 // - The next CSS chunk syntactically needs to be at the start of a stylesheet (T37562).
697 if ( !nextCssBuffer || nextCssBuffer.active === false || cssText.slice( 0, '@import'.length ) === '@import' ) {
698 nextCssBuffer = {
699 cssText: '',
700 callbacks: [],
701 active: null
702 };
703 }
704
705 // Linebreak for somewhat distinguishable sections
706 nextCssBuffer.cssText += '\n' + cssText;
707 nextCssBuffer.callbacks.push( callback );
708
709 if ( nextCssBuffer.active === null ) {
710 nextCssBuffer.active = true;
711 // The flushCssBuffer callback has its parameter bound by reference, which means
712 // 1) We can still extend the buffer from our object reference after this point.
713 // 2) We can safely re-assign the variable (not the object) to start a new buffer.
714 rAF( flushCssBuffer.bind( null, nextCssBuffer ) );
715 }
716 }
717
718 /**
719 * @private
720 * @param {Array} modules List of module names
721 * @return {string} Hash of concatenated version hashes.
722 */
723 function getCombinedVersion( modules ) {
724 var hashes = modules.reduce( function ( result, module ) {
725 return result + registry[ module ].version;
726 }, '' );
727 return fnv132( hashes );
728 }
729
730 /**
731 * Determine whether all dependencies are in state 'ready', which means we may
732 * execute the module or job now.
733 *
734 * @private
735 * @param {Array} modules Names of modules to be checked
736 * @return {boolean} True if all modules are in state 'ready', false otherwise
737 */
738 function allReady( modules ) {
739 var i;
740 for ( i = 0; i < modules.length; i++ ) {
741 if ( mw.loader.getState( modules[ i ] ) !== 'ready' ) {
742 return false;
743 }
744 }
745 return true;
746 }
747
748 /**
749 * Determine whether all direct and base dependencies are in state 'ready'
750 *
751 * @private
752 * @param {string} module Name of the module to be checked
753 * @return {boolean} True if all direct/base dependencies are in state 'ready'; false otherwise
754 */
755 function allWithImplicitReady( module ) {
756 return allReady( registry[ module ].dependencies ) &&
757 ( baseModules.indexOf( module ) !== -1 || allReady( baseModules ) );
758 }
759
760 /**
761 * Determine whether all dependencies are in state 'ready', which means we may
762 * execute the module or job now.
763 *
764 * @private
765 * @param {Array} modules Names of modules to be checked
766 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
767 */
768 function anyFailed( modules ) {
769 var i, state;
770 for ( i = 0; i < modules.length; i++ ) {
771 state = mw.loader.getState( modules[ i ] );
772 if ( state === 'error' || state === 'missing' ) {
773 return true;
774 }
775 }
776 return false;
777 }
778
779 /**
780 * A module has entered state 'ready', 'error', or 'missing'. Automatically update
781 * pending jobs and modules that depend upon this module. If the given module failed,
782 * propagate the 'error' state up the dependency tree. Otherwise, go ahead and execute
783 * all jobs/modules now having their dependencies satisfied.
784 *
785 * Jobs that depend on a failed module, will have their error callback ran (if any).
786 *
787 * @private
788 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
789 */
790 function handlePending( module ) {
791 var j, job, hasErrors, m, stateChange, fromBaseModule;
792
793 if ( registry[ module ].state === 'error' || registry[ module ].state === 'missing' ) {
794 fromBaseModule = baseModules.indexOf( module ) !== -1;
795 // If the current module failed, mark all dependent modules also as failed.
796 // Iterate until steady-state to propagate the error state upwards in the
797 // dependency tree.
798 do {
799 stateChange = false;
800 for ( m in registry ) {
801 if ( registry[ m ].state !== 'error' && registry[ m ].state !== 'missing' ) {
802 // Always propagate errors from base modules to regular modules (implicit dependency).
803 // Between base modules or regular modules, consider direct dependencies only.
804 if (
805 ( fromBaseModule && baseModules.indexOf( m ) === -1 ) ||
806 anyFailed( registry[ m ].dependencies )
807 ) {
808 registry[ m ].state = 'error';
809 stateChange = true;
810 }
811 }
812 }
813 } while ( stateChange );
814 }
815
816 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
817 for ( j = 0; j < jobs.length; j++ ) {
818 hasErrors = anyFailed( jobs[ j ].dependencies );
819 if ( hasErrors || allReady( jobs[ j ].dependencies ) ) {
820 // All dependencies satisfied, or some have errors
821 job = jobs[ j ];
822 jobs.splice( j, 1 );
823 j -= 1;
824 try {
825 if ( hasErrors ) {
826 if ( typeof job.error === 'function' ) {
827 job.error( new Error( 'Module ' + module + ' has failed dependencies' ), [ module ] );
828 }
829 } else {
830 if ( typeof job.ready === 'function' ) {
831 job.ready();
832 }
833 }
834 } catch ( e ) {
835 // A user-defined callback raised an exception.
836 // Swallow it to protect our state machine!
837 mw.trackError( 'resourceloader.exception', {
838 exception: e,
839 module: module,
840 source: 'load-callback'
841 } );
842 }
843 }
844 }
845
846 // The current module became 'ready'.
847 if ( registry[ module ].state === 'ready' ) {
848 // Save it to the module store.
849 mw.loader.store.set( module, registry[ module ] );
850 // Recursively execute all dependent modules that were already loaded
851 // (waiting for execution) and no longer have unsatisfied dependencies.
852 for ( m in registry ) {
853 // Base modules may have dependencies amongst eachother to ensure correct
854 // execution order. Regular modules wait for all base modules.
855 if ( registry[ m ].state === 'loaded' && allWithImplicitReady( m ) ) {
856 // eslint-disable-next-line no-use-before-define
857 execute( m );
858 }
859 }
860 }
861 }
862
863 /**
864 * Resolve dependencies and detect circular references.
865 *
866 * @private
867 * @param {string} module Name of the top-level module whose dependencies shall be
868 * resolved and sorted.
869 * @param {Array} resolved Returns a topological sort of the given module and its
870 * dependencies, such that later modules depend on earlier modules. The array
871 * contains the module names. If the array contains already some module names,
872 * this function appends its result to the pre-existing array.
873 * @param {StringSet} [unresolved] Used to track the current dependency
874 * chain, and to report loops in the dependency graph.
875 * @throws {Error} If any unregistered module or a dependency loop is encountered
876 */
877 function sortDependencies( module, resolved, unresolved ) {
878 var i, deps, skip;
879
880 if ( !hasOwn.call( registry, module ) ) {
881 throw new Error( 'Unknown dependency: ' + module );
882 }
883
884 if ( registry[ module ].skip !== null ) {
885 // eslint-disable-next-line no-new-func
886 skip = new Function( registry[ module ].skip );
887 registry[ module ].skip = null;
888 if ( skip() ) {
889 registry[ module ].skipped = true;
890 registry[ module ].dependencies = [];
891 registry[ module ].state = 'ready';
892 handlePending( module );
893 return;
894 }
895 }
896
897 if ( resolved.indexOf( module ) !== -1 ) {
898 // Module already resolved; nothing to do
899 return;
900 }
901 // Create unresolved if not passed in
902 if ( !unresolved ) {
903 unresolved = new StringSet();
904 }
905
906 // Add base modules
907 if ( baseModules.indexOf( module ) === -1 ) {
908 baseModules.forEach( function ( baseModule ) {
909 if ( resolved.indexOf( baseModule ) === -1 ) {
910 resolved.push( baseModule );
911 }
912 } );
913 }
914
915 // Tracks down dependencies
916 deps = registry[ module ].dependencies;
917 unresolved.add( module );
918 for ( i = 0; i < deps.length; i++ ) {
919 if ( resolved.indexOf( deps[ i ] ) === -1 ) {
920 if ( unresolved.has( deps[ i ] ) ) {
921 throw new Error(
922 'Circular reference detected: ' + module + ' -> ' + deps[ i ]
923 );
924 }
925
926 sortDependencies( deps[ i ], resolved, unresolved );
927 }
928 }
929 resolved.push( module );
930 }
931
932 /**
933 * Get names of module that a module depends on, in their proper dependency order.
934 *
935 * @private
936 * @param {string[]} modules Array of string module names
937 * @return {Array} List of dependencies, including 'module'.
938 * @throws {Error} If an unregistered module or a dependency loop is encountered
939 */
940 function resolve( modules ) {
941 var i, resolved = [];
942 for ( i = 0; i < modules.length; i++ ) {
943 sortDependencies( modules[ i ], resolved );
944 }
945 return resolved;
946 }
947
948 /**
949 * Like #resolve(), except it will silently ignore modules that
950 * are missing or have missing dependencies.
951 *
952 * @private
953 * @param {string[]} modules Array of string module names
954 * @return {Array} List of dependencies.
955 */
956 function resolveStubbornly( modules ) {
957 var i, saved, resolved = [];
958 for ( i = 0; i < modules.length; i++ ) {
959 saved = resolved.slice();
960 try {
961 sortDependencies( modules[ i ], resolved );
962 } catch ( err ) {
963 // This module is unknown or has unknown dependencies.
964 // Undo any incomplete resolutions made and keep going.
965 resolved = saved;
966 mw.trackError( 'resourceloader.exception', {
967 exception: err,
968 source: 'resolve'
969 } );
970 }
971 }
972 return resolved;
973 }
974
975 /**
976 * Load and execute a script.
977 *
978 * @private
979 * @param {string} src URL to script, will be used as the src attribute in the script tag
980 * @param {Function} [callback] Callback to run after request resolution
981 */
982 function addScript( src, callback ) {
983 var script = document.createElement( 'script' );
984 script.src = src;
985 script.onload = script.onerror = function () {
986 if ( script.parentNode ) {
987 script.parentNode.removeChild( script );
988 }
989 script = null;
990 if ( callback ) {
991 callback();
992 callback = null;
993 }
994 };
995 document.head.appendChild( script );
996 }
997
998 /**
999 * Queue the loading and execution of a script for a particular module.
1000 *
1001 * This does for debug mode what runScript() does for production.
1002 *
1003 * @private
1004 * @param {string} src URL of the script
1005 * @param {string} moduleName Name of currently executing module
1006 * @param {Function} callback Callback to run after addScript() resolution
1007 */
1008 function queueModuleScript( src, moduleName, callback ) {
1009 pendingRequests.push( function () {
1010 // Keep in sync with execute()/runScript().
1011 if ( moduleName !== 'jquery' && hasOwn.call( registry, moduleName ) ) {
1012 window.require = mw.loader.require;
1013 window.module = registry[ moduleName ].module;
1014 }
1015 addScript( src, function () {
1016 // 'module.exports' should not persist after the file is executed to
1017 // avoid leakage to unrelated code. 'require' should be kept, however,
1018 // as asynchronous access to 'require' is allowed and expected. (T144879)
1019 delete window.module;
1020 callback();
1021 // Start the next one (if any)
1022 if ( pendingRequests[ 0 ] ) {
1023 pendingRequests.shift()();
1024 } else {
1025 handlingPendingRequests = false;
1026 }
1027 } );
1028 } );
1029 if ( !handlingPendingRequests && pendingRequests[ 0 ] ) {
1030 handlingPendingRequests = true;
1031 pendingRequests.shift()();
1032 }
1033 }
1034
1035 /**
1036 * Utility function for execute()
1037 *
1038 * @ignore
1039 * @param {string} [media] Media attribute
1040 * @param {string} url URL
1041 */
1042 function addLink( media, url ) {
1043 var el = document.createElement( 'link' );
1044
1045 el.rel = 'stylesheet';
1046 if ( media && media !== 'all' ) {
1047 el.media = media;
1048 }
1049 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1050 // see #addEmbeddedCSS, T33676, T43331, and T49277 for details.
1051 el.href = url;
1052
1053 if ( marker && marker.parentNode ) {
1054 marker.parentNode.insertBefore( el, marker );
1055 } else {
1056 document.head.appendChild( el );
1057 }
1058 }
1059
1060 /**
1061 * @private
1062 * @param {string} code JavaScript code
1063 */
1064 function domEval( code ) {
1065 var script = document.createElement( 'script' );
1066 if ( mw.config.get( 'wgCSPNonce' ) !== false ) {
1067 script.nonce = mw.config.get( 'wgCSPNonce' );
1068 }
1069 script.text = code;
1070 document.head.appendChild( script );
1071 script.parentNode.removeChild( script );
1072 }
1073
1074 /**
1075 * Add one or more modules to the module load queue.
1076 *
1077 * See also #work().
1078 *
1079 * @private
1080 * @param {string[]} dependencies Array of module names in the registry
1081 * @param {Function} [ready] Callback to execute when all dependencies are ready
1082 * @param {Function} [error] Callback to execute when any dependency fails
1083 */
1084 function enqueue( dependencies, ready, error ) {
1085 if ( allReady( dependencies ) ) {
1086 // Run ready immediately
1087 if ( ready !== undefined ) {
1088 ready();
1089 }
1090 return;
1091 }
1092
1093 if ( anyFailed( dependencies ) ) {
1094 if ( error !== undefined ) {
1095 // Execute error immediately if any dependencies have errors
1096 error(
1097 new Error( 'One or more dependencies failed to load' ),
1098 dependencies
1099 );
1100 }
1101 return;
1102 }
1103
1104 // Not all dependencies are ready, add to the load queue...
1105
1106 // Add ready and error callbacks if they were given
1107 if ( ready !== undefined || error !== undefined ) {
1108 jobs.push( {
1109 // Narrow down the list to modules that are worth waiting for
1110 dependencies: dependencies.filter( function ( module ) {
1111 var state = registry[ module ].state;
1112 return state === 'registered' || state === 'loaded' || state === 'loading' || state === 'executing';
1113 } ),
1114 ready: ready,
1115 error: error
1116 } );
1117 }
1118
1119 dependencies.forEach( function ( module ) {
1120 // Only queue modules that are still in the initial 'registered' state
1121 // (not ones already loading, ready or error).
1122 if ( registry[ module ].state === 'registered' && queue.indexOf( module ) === -1 ) {
1123 // Private modules must be embedded in the page. Don't bother queuing
1124 // these as the server will deny them anyway (T101806).
1125 if ( registry[ module ].group === 'private' ) {
1126 registry[ module ].state = 'error';
1127 handlePending( module );
1128 return;
1129 }
1130 queue.push( module );
1131 }
1132 } );
1133
1134 mw.loader.work();
1135 }
1136
1137 /**
1138 * Executes a loaded module, making it ready to use
1139 *
1140 * @private
1141 * @param {string} module Module name to execute
1142 */
1143 function execute( module ) {
1144 var key, value, media, i, urls, cssHandle, checkCssHandles, runScript,
1145 cssHandlesRegistered = false;
1146
1147 if ( !hasOwn.call( registry, module ) ) {
1148 throw new Error( 'Module has not been registered yet: ' + module );
1149 }
1150 if ( registry[ module ].state !== 'loaded' ) {
1151 throw new Error( 'Module in state "' + registry[ module ].state + '" may not be executed: ' + module );
1152 }
1153
1154 registry[ module ].state = 'executing';
1155 $CODE.profileExecuteStart();
1156
1157 runScript = function () {
1158 var script, markModuleReady, nestedAddScript;
1159
1160 $CODE.profileScriptStart();
1161 script = registry[ module ].script;
1162 markModuleReady = function () {
1163 $CODE.profileScriptEnd();
1164 registry[ module ].state = 'ready';
1165 handlePending( module );
1166 };
1167 nestedAddScript = function ( arr, callback, i ) {
1168 // Recursively call queueModuleScript() in its own callback
1169 // for each element of arr.
1170 if ( i >= arr.length ) {
1171 // We're at the end of the array
1172 callback();
1173 return;
1174 }
1175
1176 queueModuleScript( arr[ i ], module, function () {
1177 nestedAddScript( arr, callback, i + 1 );
1178 } );
1179 };
1180
1181 try {
1182 if ( Array.isArray( script ) ) {
1183 nestedAddScript( script, markModuleReady, 0 );
1184 } else if ( typeof script === 'function' ) {
1185 // Keep in sync with queueModuleScript() for debug mode
1186 if ( module === 'jquery' ) {
1187 // This is a special case for when 'jquery' itself is being loaded.
1188 // - The standard jquery.js distribution does not set `window.jQuery`
1189 // in CommonJS-compatible environments (Node.js, AMD, RequireJS, etc.).
1190 // - MediaWiki's 'jquery' module also bundles jquery.migrate.js, which
1191 // in a CommonJS-compatible environment, will use require('jquery'),
1192 // but that can't work when we're still inside that module.
1193 script();
1194 } else {
1195 // Pass jQuery twice so that the signature of the closure which wraps
1196 // the script can bind both '$' and 'jQuery'.
1197 script( window.$, window.$, mw.loader.require, registry[ module ].module );
1198 }
1199 markModuleReady();
1200
1201 } else if ( typeof script === 'string' ) {
1202 // Site and user modules are legacy scripts that run in the global scope.
1203 // This is transported as a string instead of a function to avoid needing
1204 // to use string manipulation to undo the function wrapper.
1205 domEval( script );
1206 markModuleReady();
1207
1208 } else {
1209 // Module without script
1210 markModuleReady();
1211 }
1212 } catch ( e ) {
1213 // Use mw.track instead of mw.log because these errors are common in production mode
1214 // (e.g. undefined variable), and mw.log is only enabled in debug mode.
1215 registry[ module ].state = 'error';
1216 $CODE.profileScriptEnd();
1217 mw.trackError( 'resourceloader.exception', {
1218 exception: e, module:
1219 module, source: 'module-execute'
1220 } );
1221 handlePending( module );
1222 }
1223 };
1224
1225 // Add localizations to message system
1226 if ( registry[ module ].messages ) {
1227 mw.messages.set( registry[ module ].messages );
1228 }
1229
1230 // Initialise templates
1231 if ( registry[ module ].templates ) {
1232 mw.templates.set( module, registry[ module ].templates );
1233 }
1234
1235 // Make sure we don't run the scripts until all stylesheet insertions have completed.
1236 ( function () {
1237 var pending = 0;
1238 checkCssHandles = function () {
1239 var ex, dependencies;
1240 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
1241 // one of the cssHandles is fired while we're still creating more handles.
1242 if ( cssHandlesRegistered && pending === 0 && runScript ) {
1243 if ( module === 'user' ) {
1244 // Implicit dependency on the site module. Not real dependency because
1245 // it should run after 'site' regardless of whether it succeeds or fails.
1246 // Note: This is a simplified version of mw.loader.using(), inlined here
1247 // as using() depends on jQuery (T192623).
1248 try {
1249 dependencies = resolve( [ 'site' ] );
1250 } catch ( e ) {
1251 ex = e;
1252 runScript();
1253 }
1254 if ( ex === undefined ) {
1255 enqueue( dependencies, runScript, runScript );
1256 }
1257 } else {
1258 runScript();
1259 }
1260 runScript = undefined; // Revoke
1261 }
1262 };
1263 cssHandle = function () {
1264 var check = checkCssHandles;
1265 pending++;
1266 return function () {
1267 if ( check ) {
1268 pending--;
1269 check();
1270 check = undefined; // Revoke
1271 }
1272 };
1273 };
1274 }() );
1275
1276 // Process styles (see also mw.loader.implement)
1277 // * back-compat: { <media>: css }
1278 // * back-compat: { <media>: [url, ..] }
1279 // * { "css": [css, ..] }
1280 // * { "url": { <media>: [url, ..] } }
1281 if ( registry[ module ].style ) {
1282 for ( key in registry[ module ].style ) {
1283 value = registry[ module ].style[ key ];
1284 media = undefined;
1285
1286 if ( key !== 'url' && key !== 'css' ) {
1287 // Backwards compatibility, key is a media-type
1288 if ( typeof value === 'string' ) {
1289 // back-compat: { <media>: css }
1290 // Ignore 'media' because it isn't supported (nor was it used).
1291 // Strings are pre-wrapped in "@media". The media-type was just ""
1292 // (because it had to be set to something).
1293 // This is one of the reasons why this format is no longer used.
1294 addEmbeddedCSS( value, cssHandle() );
1295 } else {
1296 // back-compat: { <media>: [url, ..] }
1297 media = key;
1298 key = 'bc-url';
1299 }
1300 }
1301
1302 // Array of css strings in key 'css',
1303 // or back-compat array of urls from media-type
1304 if ( Array.isArray( value ) ) {
1305 for ( i = 0; i < value.length; i++ ) {
1306 if ( key === 'bc-url' ) {
1307 // back-compat: { <media>: [url, ..] }
1308 addLink( media, value[ i ] );
1309 } else if ( key === 'css' ) {
1310 // { "css": [css, ..] }
1311 addEmbeddedCSS( value[ i ], cssHandle() );
1312 }
1313 }
1314 // Not an array, but a regular object
1315 // Array of urls inside media-type key
1316 } else if ( typeof value === 'object' ) {
1317 // { "url": { <media>: [url, ..] } }
1318 for ( media in value ) {
1319 urls = value[ media ];
1320 for ( i = 0; i < urls.length; i++ ) {
1321 addLink( media, urls[ i ] );
1322 }
1323 }
1324 }
1325 }
1326 }
1327
1328 // End profiling of execute()-self before we call checkCssHandles(),
1329 // which (sometimes asynchronously) calls runScript(), which we want
1330 // to measure separately without overlap.
1331 $CODE.profileExecuteEnd();
1332
1333 // Kick off.
1334 cssHandlesRegistered = true;
1335 checkCssHandles();
1336 }
1337
1338 function sortQuery( o ) {
1339 var key,
1340 sorted = {},
1341 a = [];
1342
1343 for ( key in o ) {
1344 a.push( key );
1345 }
1346 a.sort();
1347 for ( key = 0; key < a.length; key++ ) {
1348 sorted[ a[ key ] ] = o[ a[ key ] ];
1349 }
1350 return sorted;
1351 }
1352
1353 /**
1354 * Converts a module map of the form `{ foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }`
1355 * to a query string of the form `foo.bar,baz|bar.baz,quux`.
1356 *
1357 * See `ResourceLoader::makePackedModulesString()` in PHP, of which this is a port.
1358 * On the server, unpacking is done by `ResourceLoaderContext::expandModuleNames()`.
1359 *
1360 * Note: This is only half of the logic, the other half has to be in #batchRequest(),
1361 * because its implementation needs to keep track of potential string size in order
1362 * to decide when to split the requests due to url size.
1363 *
1364 * @private
1365 * @param {Object} moduleMap Module map
1366 * @return {Object}
1367 * @return {string} return.str Module query string
1368 * @return {Array} return.list List of module names in matching order
1369 */
1370 function buildModulesString( moduleMap ) {
1371 var p, prefix,
1372 str = [],
1373 list = [];
1374
1375 function restore( suffix ) {
1376 return p + suffix;
1377 }
1378
1379 for ( prefix in moduleMap ) {
1380 p = prefix === '' ? '' : prefix + '.';
1381 str.push( p + moduleMap[ prefix ].join( ',' ) );
1382 list.push.apply( list, moduleMap[ prefix ].map( restore ) );
1383 }
1384 return {
1385 str: str.join( '|' ),
1386 list: list
1387 };
1388 }
1389
1390 /**
1391 * Resolve indexed dependencies.
1392 *
1393 * ResourceLoader uses an optimization to save space which replaces module names in
1394 * dependency lists with the index of that module within the array of module
1395 * registration data if it exists. The benefit is a significant reduction in the data
1396 * size of the startup module. This function changes those dependency lists back to
1397 * arrays of strings.
1398 *
1399 * @private
1400 * @param {Array} modules Modules array
1401 */
1402 function resolveIndexedDependencies( modules ) {
1403 var i, j, deps;
1404 function resolveIndex( dep ) {
1405 return typeof dep === 'number' ? modules[ dep ][ 0 ] : dep;
1406 }
1407 for ( i = 0; i < modules.length; i++ ) {
1408 deps = modules[ i ][ 2 ];
1409 if ( deps ) {
1410 for ( j = 0; j < deps.length; j++ ) {
1411 deps[ j ] = resolveIndex( deps[ j ] );
1412 }
1413 }
1414 }
1415 }
1416
1417 /**
1418 * @private
1419 * @param {Object} params Map of parameter names to values
1420 * @return {string}
1421 */
1422 function makeQueryString( params ) {
1423 return Object.keys( params ).map( function ( key ) {
1424 return encodeURIComponent( key ) + '=' + encodeURIComponent( params[ key ] );
1425 } ).join( '&' );
1426 }
1427
1428 /**
1429 * Create network requests for a batch of modules.
1430 *
1431 * This is an internal method for #work(). This must not be called directly
1432 * unless the modules are already registered, and no request is in progress,
1433 * and the module state has already been set to `loading`.
1434 *
1435 * @private
1436 * @param {string[]} batch
1437 */
1438 function batchRequest( batch ) {
1439 var reqBase, splits, maxQueryLength, b, bSource, bGroup,
1440 source, group, i, modules, sourceLoadScript,
1441 currReqBase, currReqBaseLength, moduleMap, currReqModules, l,
1442 lastDotIndex, prefix, suffix, bytesAdded;
1443
1444 /**
1445 * Start the currently drafted request to the server.
1446 *
1447 * @ignore
1448 */
1449 function doRequest() {
1450 // Optimisation: Inherit (Object.create), not copy ($.extend)
1451 var query = Object.create( currReqBase ),
1452 packed = buildModulesString( moduleMap );
1453 query.modules = packed.str;
1454 // The packing logic can change the effective order, even if the input was
1455 // sorted. As such, the call to getCombinedVersion() must use this
1456 // effective order, instead of currReqModules, as otherwise the combined
1457 // version will not match the hash expected by the server based on
1458 // combining versions from the module query string in-order. (T188076)
1459 query.version = getCombinedVersion( packed.list );
1460 query = sortQuery( query );
1461 addScript( sourceLoadScript + '?' + makeQueryString( query ) );
1462 }
1463
1464 if ( !batch.length ) {
1465 return;
1466 }
1467
1468 // Always order modules alphabetically to help reduce cache
1469 // misses for otherwise identical content.
1470 batch.sort();
1471
1472 // Query parameters common to all requests
1473 reqBase = {
1474 skin: mw.config.get( 'skin' ),
1475 lang: mw.config.get( 'wgUserLanguage' ),
1476 debug: mw.config.get( 'debug' )
1477 };
1478 maxQueryLength = mw.config.get( 'wgResourceLoaderMaxQueryLength', 2000 );
1479
1480 // Split module list by source and by group.
1481 splits = Object.create( null );
1482 for ( b = 0; b < batch.length; b++ ) {
1483 bSource = registry[ batch[ b ] ].source;
1484 bGroup = registry[ batch[ b ] ].group;
1485 if ( !splits[ bSource ] ) {
1486 splits[ bSource ] = Object.create( null );
1487 }
1488 if ( !splits[ bSource ][ bGroup ] ) {
1489 splits[ bSource ][ bGroup ] = [];
1490 }
1491 splits[ bSource ][ bGroup ].push( batch[ b ] );
1492 }
1493
1494 for ( source in splits ) {
1495 sourceLoadScript = sources[ source ];
1496
1497 for ( group in splits[ source ] ) {
1498
1499 // Cache access to currently selected list of
1500 // modules for this group from this source.
1501 modules = splits[ source ][ group ];
1502
1503 // Query parameters common to requests for this module group
1504 // Optimisation: Inherit (Object.create), not copy ($.extend)
1505 currReqBase = Object.create( reqBase );
1506 // User modules require a user name in the query string.
1507 if ( group === 'user' && mw.config.get( 'wgUserName' ) !== null ) {
1508 currReqBase.user = mw.config.get( 'wgUserName' );
1509 }
1510
1511 // In addition to currReqBase, doRequest() will also add 'modules' and 'version'.
1512 // > '&modules='.length === 9
1513 // > '&version=1234567'.length === 16
1514 // > 9 + 16 = 25
1515 currReqBaseLength = makeQueryString( currReqBase ).length + 25;
1516
1517 // We may need to split up the request to honor the query string length limit,
1518 // so build it piece by piece.
1519 l = currReqBaseLength;
1520 moduleMap = Object.create( null ); // { prefix: [ suffixes ] }
1521 currReqModules = [];
1522
1523 for ( i = 0; i < modules.length; i++ ) {
1524 // Determine how many bytes this module would add to the query string
1525 lastDotIndex = modules[ i ].lastIndexOf( '.' );
1526 // If lastDotIndex is -1, substr() returns an empty string
1527 prefix = modules[ i ].substr( 0, lastDotIndex );
1528 suffix = modules[ i ].slice( lastDotIndex + 1 );
1529 bytesAdded = moduleMap[ prefix ] ?
1530 suffix.length + 3 : // '%2C'.length == 3
1531 modules[ i ].length + 3; // '%7C'.length == 3
1532
1533 // If the url would become too long, create a new one, but don't create empty requests
1534 if ( maxQueryLength > 0 && currReqModules.length && l + bytesAdded > maxQueryLength ) {
1535 // Dispatch what we've got...
1536 doRequest();
1537 // .. and start again.
1538 l = currReqBaseLength;
1539 moduleMap = Object.create( null );
1540 currReqModules = [];
1541
1542 mw.track( 'resourceloader.splitRequest', { maxQueryLength: maxQueryLength } );
1543 }
1544 if ( !moduleMap[ prefix ] ) {
1545 moduleMap[ prefix ] = [];
1546 }
1547 l += bytesAdded;
1548 moduleMap[ prefix ].push( suffix );
1549 currReqModules.push( modules[ i ] );
1550 }
1551 // If there's anything left in moduleMap, request that too
1552 if ( currReqModules.length ) {
1553 doRequest();
1554 }
1555 }
1556 }
1557 }
1558
1559 /**
1560 * @private
1561 * @param {string[]} implementations Array containing pieces of JavaScript code in the
1562 * form of calls to mw.loader#implement().
1563 * @param {Function} cb Callback in case of failure
1564 * @param {Error} cb.err
1565 */
1566 function asyncEval( implementations, cb ) {
1567 if ( !implementations.length ) {
1568 return;
1569 }
1570 mw.requestIdleCallback( function () {
1571 try {
1572 domEval( implementations.join( ';' ) );
1573 } catch ( err ) {
1574 cb( err );
1575 }
1576 } );
1577 }
1578
1579 /**
1580 * Make a versioned key for a specific module.
1581 *
1582 * @private
1583 * @param {string} module Module name
1584 * @return {string|null} Module key in format '`[name]@[version]`',
1585 * or null if the module does not exist
1586 */
1587 function getModuleKey( module ) {
1588 return hasOwn.call( registry, module ) ?
1589 ( module + '@' + registry[ module ].version ) : null;
1590 }
1591
1592 /**
1593 * @private
1594 * @param {string} key Module name or '`[name]@[version]`'
1595 * @return {Object}
1596 */
1597 function splitModuleKey( key ) {
1598 var index = key.indexOf( '@' );
1599 if ( index === -1 ) {
1600 return {
1601 name: key,
1602 version: ''
1603 };
1604 }
1605 return {
1606 name: key.slice( 0, index ),
1607 version: key.slice( index + 1 )
1608 };
1609 }
1610
1611 /* Public Members */
1612 return {
1613 /**
1614 * The module registry is exposed as an aid for debugging and inspecting page
1615 * state; it is not a public interface for modifying the registry.
1616 *
1617 * @see #registry
1618 * @property
1619 * @private
1620 */
1621 moduleRegistry: registry,
1622
1623 /**
1624 * @inheritdoc #newStyleTag
1625 * @method
1626 */
1627 addStyleTag: newStyleTag,
1628
1629 enqueue: enqueue,
1630
1631 resolve: resolve,
1632
1633 /**
1634 * Start loading of all queued module dependencies.
1635 *
1636 * @protected
1637 */
1638 work: function () {
1639 var q, batch, implementations, sourceModules;
1640
1641 batch = [];
1642
1643 // Appends a list of modules from the queue to the batch
1644 for ( q = 0; q < queue.length; q++ ) {
1645 // Only load modules which are registered
1646 if ( hasOwn.call( registry, queue[ q ] ) && registry[ queue[ q ] ].state === 'registered' ) {
1647 // Prevent duplicate entries
1648 if ( batch.indexOf( queue[ q ] ) === -1 ) {
1649 batch.push( queue[ q ] );
1650 // Mark registered modules as loading
1651 registry[ queue[ q ] ].state = 'loading';
1652 }
1653 }
1654 }
1655
1656 // Now that the queue has been processed into a batch, clear the queue.
1657 // This MUST happen before we initiate any eval or network request. Otherwise,
1658 // it is possible for a cached script to instantly trigger the same work queue
1659 // again; all before we've cleared it causing each request to include modules
1660 // which are already loaded.
1661 queue = [];
1662
1663 if ( !batch.length ) {
1664 return;
1665 }
1666
1667 mw.loader.store.init();
1668 if ( mw.loader.store.enabled ) {
1669 implementations = [];
1670 sourceModules = [];
1671 batch = batch.filter( function ( module ) {
1672 var implementation = mw.loader.store.get( module );
1673 if ( implementation ) {
1674 implementations.push( implementation );
1675 sourceModules.push( module );
1676 return false;
1677 }
1678 return true;
1679 } );
1680 asyncEval( implementations, function ( err ) {
1681 var failed;
1682 // Not good, the cached mw.loader.implement calls failed! This should
1683 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1684 // Depending on how corrupt the string is, it is likely that some
1685 // modules' implement() succeeded while the ones after the error will
1686 // never run and leave their modules in the 'loading' state forever.
1687 mw.loader.store.stats.failed++;
1688
1689 // Since this is an error not caused by an individual module but by
1690 // something that infected the implement call itself, don't take any
1691 // risks and clear everything in this cache.
1692 mw.loader.store.clear();
1693
1694 mw.trackError( 'resourceloader.exception', {
1695 exception: err,
1696 source: 'store-eval'
1697 } );
1698 // Re-add the failed ones that are still pending back to the batch
1699 failed = sourceModules.filter( function ( module ) {
1700 return registry[ module ].state === 'loading';
1701 } );
1702 batchRequest( failed );
1703 } );
1704 }
1705
1706 batchRequest( batch );
1707 },
1708
1709 /**
1710 * Register a source.
1711 *
1712 * The #work() method will use this information to split up requests by source.
1713 *
1714 * mw.loader.addSource( 'mediawikiwiki', '//www.mediawiki.org/w/load.php' );
1715 *
1716 * @param {string|Object} id Source ID, or object mapping ids to load urls
1717 * @param {string} loadUrl Url to a load.php end point
1718 * @throws {Error} If source id is already registered
1719 */
1720 addSource: function ( id, loadUrl ) {
1721 var source;
1722 // Allow multiple additions
1723 if ( typeof id === 'object' ) {
1724 for ( source in id ) {
1725 mw.loader.addSource( source, id[ source ] );
1726 }
1727 return;
1728 }
1729
1730 if ( hasOwn.call( sources, id ) ) {
1731 throw new Error( 'source already registered: ' + id );
1732 }
1733
1734 sources[ id ] = loadUrl;
1735 },
1736
1737 /**
1738 * Register a module, letting the system know about it and its properties.
1739 *
1740 * The startup modules contain calls to this method.
1741 *
1742 * When using multiple module registration by passing an array, dependencies that
1743 * are specified as references to modules within the array will be resolved before
1744 * the modules are registered.
1745 *
1746 * @param {string|Array} module Module name or array of arrays, each containing
1747 * a list of arguments compatible with this method
1748 * @param {string|number} version Module version hash (falls backs to empty string)
1749 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1750 * @param {string[]} [dependencies] Array of module names on which this module depends.
1751 * @param {string} [group=null] Group which the module is in
1752 * @param {string} [source='local'] Name of the source
1753 * @param {string} [skip=null] Script body of the skip function
1754 */
1755 register: function ( module, version, dependencies, group, source, skip ) {
1756 var i;
1757 // Allow multiple registration
1758 if ( typeof module === 'object' ) {
1759 resolveIndexedDependencies( module );
1760 for ( i = 0; i < module.length; i++ ) {
1761 // module is an array of module names
1762 if ( typeof module[ i ] === 'string' ) {
1763 mw.loader.register( module[ i ] );
1764 // module is an array of arrays
1765 } else if ( typeof module[ i ] === 'object' ) {
1766 mw.loader.register.apply( mw.loader, module[ i ] );
1767 }
1768 }
1769 return;
1770 }
1771 if ( hasOwn.call( registry, module ) ) {
1772 throw new Error( 'module already registered: ' + module );
1773 }
1774 // List the module as registered
1775 registry[ module ] = {
1776 // Exposed to execute() for mw.loader.implement() closures.
1777 // Import happens via require().
1778 module: {
1779 exports: {}
1780 },
1781 version: String( version || '' ),
1782 dependencies: dependencies || [],
1783 group: typeof group === 'string' ? group : null,
1784 source: typeof source === 'string' ? source : 'local',
1785 state: 'registered',
1786 skip: typeof skip === 'string' ? skip : null
1787 };
1788 },
1789
1790 /**
1791 * Implement a module given the components that make up the module.
1792 *
1793 * When #load() or #using() requests one or more modules, the server
1794 * response contain calls to this function.
1795 *
1796 * @param {string} module Name of module and current module version. Formatted
1797 * as '`[name]@[version]`". This version should match the requested version
1798 * (from #batchRequest and #registry). This avoids race conditions (T117587).
1799 * For back-compat with MediaWiki 1.27 and earlier, the version may be omitted.
1800 * @param {Function|Array|string} [script] Function with module code, list of URLs
1801 * to load via `<script src>`, or string of module code for `$.globalEval()`.
1802 * @param {Object} [style] Should follow one of the following patterns:
1803 *
1804 * { "css": [css, ..] }
1805 * { "url": { <media>: [url, ..] } }
1806 *
1807 * And for backwards compatibility (needs to be supported forever due to caching):
1808 *
1809 * { <media>: css }
1810 * { <media>: [url, ..] }
1811 *
1812 * The reason css strings are not concatenated anymore is T33676. We now check
1813 * whether it's safe to extend the stylesheet.
1814 *
1815 * @protected
1816 * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1817 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1818 */
1819 implement: function ( module, script, style, messages, templates ) {
1820 var split = splitModuleKey( module ),
1821 name = split.name,
1822 version = split.version;
1823 // Automatically register module
1824 if ( !hasOwn.call( registry, name ) ) {
1825 mw.loader.register( name );
1826 }
1827 // Check for duplicate implementation
1828 if ( hasOwn.call( registry, name ) && registry[ name ].script !== undefined ) {
1829 throw new Error( 'module already implemented: ' + name );
1830 }
1831 if ( version ) {
1832 // Without this reset, if there is a version mismatch between the
1833 // requested and received module version, then mw.loader.store would
1834 // cache the response under the requested key. Thus poisoning the cache
1835 // indefinitely with a stale value. (T117587)
1836 registry[ name ].version = version;
1837 }
1838 // Attach components
1839 registry[ name ].script = script || null;
1840 registry[ name ].style = style || null;
1841 registry[ name ].messages = messages || null;
1842 registry[ name ].templates = templates || null;
1843 // The module may already have been marked as erroneous
1844 if ( registry[ name ].state !== 'error' && registry[ name ].state !== 'missing' ) {
1845 registry[ name ].state = 'loaded';
1846 if ( allWithImplicitReady( name ) ) {
1847 execute( name );
1848 }
1849 }
1850 },
1851
1852 /**
1853 * Load an external script or one or more modules.
1854 *
1855 * This method takes a list of unrelated modules. Use cases:
1856 *
1857 * - A web page will be composed of many different widgets. These widgets independently
1858 * queue their ResourceLoader modules (`OutputPage::addModules()`). If any of them
1859 * have problems, or are no longer known (e.g. cached HTML), the other modules
1860 * should still be loaded.
1861 * - This method is used for preloading, which must not throw. Later code that
1862 * calls #using() will handle the error.
1863 *
1864 * @param {string|Array} modules Either the name of a module, array of modules,
1865 * or a URL of an external script or style
1866 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
1867 * external script or style; acceptable values are "text/css" and
1868 * "text/javascript"; if no type is provided, text/javascript is assumed.
1869 */
1870 load: function ( modules, type ) {
1871 var filtered, l;
1872
1873 // Allow calling with a url or single dependency as a string
1874 if ( typeof modules === 'string' ) {
1875 // "https://example.org/x.js", "http://example.org/x.js", "//example.org/x.js", "/x.js"
1876 if ( /^(https?:)?\/?\//.test( modules ) ) {
1877 if ( type === 'text/css' ) {
1878 l = document.createElement( 'link' );
1879 l.rel = 'stylesheet';
1880 l.href = modules;
1881 document.head.appendChild( l );
1882 return;
1883 }
1884 if ( type === 'text/javascript' || type === undefined ) {
1885 addScript( modules );
1886 return;
1887 }
1888 // Unknown type
1889 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type );
1890 }
1891 // Called with single module
1892 modules = [ modules ];
1893 }
1894
1895 // Filter out top-level modules that are unknown or failed to load before.
1896 filtered = modules.filter( function ( module ) {
1897 var state = mw.loader.getState( module );
1898 return state !== 'error' && state !== 'missing';
1899 } );
1900 // Resolve remaining list using the known dependency tree.
1901 // This also filters out modules with unknown dependencies. (T36853)
1902 filtered = resolveStubbornly( filtered );
1903 // Some modules are not yet ready, add to module load queue.
1904 enqueue( filtered, undefined, undefined );
1905 },
1906
1907 /**
1908 * Change the state of one or more modules.
1909 *
1910 * @param {Object} modules Object of module name/state pairs
1911 */
1912 state: function ( modules ) {
1913 var module, state;
1914 for ( module in modules ) {
1915 state = modules[ module ];
1916 if ( !hasOwn.call( registry, module ) ) {
1917 mw.loader.register( module );
1918 }
1919 registry[ module ].state = state;
1920 if ( state === 'ready' || state === 'error' || state === 'missing' ) {
1921 // Make sure pending modules depending on this one get executed if their
1922 // dependencies are now fulfilled!
1923 handlePending( module );
1924 }
1925 }
1926 },
1927
1928 /**
1929 * Get the version of a module.
1930 *
1931 * @param {string} module Name of module
1932 * @return {string|null} The version, or null if the module (or its version) is not
1933 * in the registry.
1934 */
1935 getVersion: function ( module ) {
1936 return hasOwn.call( registry, module ) ? registry[ module ].version : null;
1937 },
1938
1939 /**
1940 * Get the state of a module.
1941 *
1942 * @param {string} module Name of module
1943 * @return {string|null} The state, or null if the module (or its state) is not
1944 * in the registry.
1945 */
1946 getState: function ( module ) {
1947 return hasOwn.call( registry, module ) ? registry[ module ].state : null;
1948 },
1949
1950 /**
1951 * Get the names of all registered modules.
1952 *
1953 * @return {Array}
1954 */
1955 getModuleNames: function () {
1956 return Object.keys( registry );
1957 },
1958
1959 /**
1960 * Get the exported value of a module.
1961 *
1962 * This static method is publicly exposed for debugging purposes
1963 * only and must not be used in production code. In production code,
1964 * please use the dynamically provided `require()` function instead.
1965 *
1966 * In case of lazy-loaded modules via mw.loader#using(), the returned
1967 * Promise provides the function, see #using() for examples.
1968 *
1969 * @private
1970 * @since 1.27
1971 * @param {string} moduleName Module name
1972 * @return {Mixed} Exported value
1973 */
1974 require: function ( moduleName ) {
1975 var state = mw.loader.getState( moduleName );
1976
1977 // Only ready modules can be required
1978 if ( state !== 'ready' ) {
1979 // Module may've forgotten to declare a dependency
1980 throw new Error( 'Module "' + moduleName + '" is not loaded.' );
1981 }
1982
1983 return registry[ moduleName ].module.exports;
1984 },
1985
1986 /**
1987 * On browsers that implement the localStorage API, the module store serves as a
1988 * smart complement to the browser cache. Unlike the browser cache, the module store
1989 * can slice a concatenated response from ResourceLoader into its constituent
1990 * modules and cache each of them separately, using each module's versioning scheme
1991 * to determine when the cache should be invalidated.
1992 *
1993 * @private
1994 * @singleton
1995 * @class mw.loader.store
1996 */
1997 store: {
1998 // Whether the store is in use on this page.
1999 enabled: null,
2000
2001 // Modules whose string representation exceeds 100 kB are
2002 // ineligible for storage. See bug T66721.
2003 MODULE_SIZE_MAX: 100 * 1000,
2004
2005 // The contents of the store, mapping '[name]@[version]' keys
2006 // to module implementations.
2007 items: {},
2008
2009 // Cache hit stats
2010 stats: { hits: 0, misses: 0, expired: 0, failed: 0 },
2011
2012 /**
2013 * Construct a JSON-serializable object representing the content of the store.
2014 *
2015 * @return {Object} Module store contents.
2016 */
2017 toJSON: function () {
2018 return { items: mw.loader.store.items, vary: mw.loader.store.getVary() };
2019 },
2020
2021 /**
2022 * Get the localStorage key for the entire module store. The key references
2023 * $wgDBname to prevent clashes between wikis which share a common host.
2024 *
2025 * @return {string} localStorage item key
2026 */
2027 getStoreKey: function () {
2028 return 'MediaWikiModuleStore:' + mw.config.get( 'wgDBname' );
2029 },
2030
2031 /**
2032 * Get a key on which to vary the module cache.
2033 *
2034 * @return {string} String of concatenated vary conditions.
2035 */
2036 getVary: function () {
2037 return mw.config.get( 'skin' ) + ':' +
2038 mw.config.get( 'wgResourceLoaderStorageVersion' ) + ':' +
2039 mw.config.get( 'wgUserLanguage' );
2040 },
2041
2042 /**
2043 * Initialize the store.
2044 *
2045 * Retrieves store from localStorage and (if successfully retrieved) decoding
2046 * the stored JSON value to a plain object.
2047 *
2048 * The try / catch block is used for JSON & localStorage feature detection.
2049 * See the in-line documentation for Modernizr's localStorage feature detection
2050 * code for a full account of why we need a try / catch:
2051 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2052 */
2053 init: function () {
2054 var raw, data;
2055
2056 if ( mw.loader.store.enabled !== null ) {
2057 // Init already ran
2058 return;
2059 }
2060
2061 if (
2062 // Disabled because localStorage quotas are tight and (in Firefox's case)
2063 // shared by multiple origins.
2064 // See T66721, and <https://bugzilla.mozilla.org/show_bug.cgi?id=1064466>.
2065 /Firefox|Opera/.test( navigator.userAgent ) ||
2066
2067 // Disabled by configuration.
2068 !mw.config.get( 'wgResourceLoaderStorageEnabled' )
2069 ) {
2070 // Clear any previous store to free up space. (T66721)
2071 mw.loader.store.clear();
2072 mw.loader.store.enabled = false;
2073 return;
2074 }
2075 if ( mw.config.get( 'debug' ) ) {
2076 // Disable module store in debug mode
2077 mw.loader.store.enabled = false;
2078 return;
2079 }
2080
2081 try {
2082 // This a string we stored, or `null` if the key does not (yet) exist.
2083 raw = localStorage.getItem( mw.loader.store.getStoreKey() );
2084 // If we get here, localStorage is available; mark enabled
2085 mw.loader.store.enabled = true;
2086 // If null, JSON.parse() will cast to string and re-parse, still null.
2087 data = JSON.parse( raw );
2088 if ( data && typeof data.items === 'object' && data.vary === mw.loader.store.getVary() ) {
2089 mw.loader.store.items = data.items;
2090 return;
2091 }
2092 } catch ( e ) {
2093 mw.trackError( 'resourceloader.exception', {
2094 exception: e,
2095 source: 'store-localstorage-init'
2096 } );
2097 }
2098
2099 // If we get here, one of four things happened:
2100 //
2101 // 1. localStorage did not contain our store key.
2102 // This means `raw` is `null`, and we're on a fresh page view (cold cache).
2103 // The store was enabled, and `items` starts fresh.
2104 //
2105 // 2. localStorage contained parseable data under our store key,
2106 // but it's not applicable to our current context (see getVary).
2107 // The store was enabled, and `items` starts fresh.
2108 //
2109 // 3. JSON.parse threw (localStorage contained corrupt data).
2110 // This means `raw` contains a string.
2111 // The store was enabled, and `items` starts fresh.
2112 //
2113 // 4. localStorage threw (disabled or otherwise unavailable).
2114 // This means `raw` was never assigned.
2115 // We will disable the store below.
2116 if ( raw === undefined ) {
2117 // localStorage failed; disable store
2118 mw.loader.store.enabled = false;
2119 }
2120 },
2121
2122 /**
2123 * Retrieve a module from the store and update cache hit stats.
2124 *
2125 * @param {string} module Module name
2126 * @return {string|boolean} Module implementation or false if unavailable
2127 */
2128 get: function ( module ) {
2129 var key;
2130
2131 if ( !mw.loader.store.enabled ) {
2132 return false;
2133 }
2134
2135 key = getModuleKey( module );
2136 if ( key in mw.loader.store.items ) {
2137 mw.loader.store.stats.hits++;
2138 return mw.loader.store.items[ key ];
2139 }
2140 mw.loader.store.stats.misses++;
2141 return false;
2142 },
2143
2144 /**
2145 * Stringify a module and queue it for storage.
2146 *
2147 * @param {string} module Module name
2148 * @param {Object} descriptor The module's descriptor as set in the registry
2149 */
2150 set: function ( module, descriptor ) {
2151 var args, key, src;
2152
2153 if ( !mw.loader.store.enabled ) {
2154 return;
2155 }
2156
2157 key = getModuleKey( module );
2158
2159 if (
2160 // Already stored a copy of this exact version
2161 key in mw.loader.store.items ||
2162 // Module failed to load
2163 descriptor.state !== 'ready' ||
2164 // Unversioned, private, or site-/user-specific
2165 !descriptor.version ||
2166 descriptor.group === 'private' ||
2167 descriptor.group === 'user' ||
2168 // Partial descriptor
2169 // (e.g. skipped module, or style module with state=ready)
2170 [ descriptor.script, descriptor.style, descriptor.messages,
2171 descriptor.templates ].indexOf( undefined ) !== -1
2172 ) {
2173 // Decline to store
2174 return;
2175 }
2176
2177 try {
2178 args = [
2179 JSON.stringify( key ),
2180 typeof descriptor.script === 'function' ?
2181 String( descriptor.script ) :
2182 JSON.stringify( descriptor.script ),
2183 JSON.stringify( descriptor.style ),
2184 JSON.stringify( descriptor.messages ),
2185 JSON.stringify( descriptor.templates )
2186 ];
2187 } catch ( e ) {
2188 mw.trackError( 'resourceloader.exception', {
2189 exception: e,
2190 source: 'store-localstorage-json'
2191 } );
2192 return;
2193 }
2194
2195 src = 'mw.loader.implement(' + args.join( ',' ) + ');';
2196 if ( src.length > mw.loader.store.MODULE_SIZE_MAX ) {
2197 return;
2198 }
2199 mw.loader.store.items[ key ] = src;
2200 mw.loader.store.update();
2201 },
2202
2203 /**
2204 * Iterate through the module store, removing any item that does not correspond
2205 * (in name and version) to an item in the module registry.
2206 */
2207 prune: function () {
2208 var key, module;
2209
2210 for ( key in mw.loader.store.items ) {
2211 module = key.slice( 0, key.indexOf( '@' ) );
2212 if ( getModuleKey( module ) !== key ) {
2213 mw.loader.store.stats.expired++;
2214 delete mw.loader.store.items[ key ];
2215 } else if ( mw.loader.store.items[ key ].length > mw.loader.store.MODULE_SIZE_MAX ) {
2216 // This value predates the enforcement of a size limit on cached modules.
2217 delete mw.loader.store.items[ key ];
2218 }
2219 }
2220 },
2221
2222 /**
2223 * Clear the entire module store right now.
2224 */
2225 clear: function () {
2226 mw.loader.store.items = {};
2227 try {
2228 localStorage.removeItem( mw.loader.store.getStoreKey() );
2229 } catch ( e ) {}
2230 },
2231
2232 /**
2233 * Sync in-memory store back to localStorage.
2234 *
2235 * This function debounces updates. When called with a flush already pending, the
2236 * scheduled flush is postponed. The call to localStorage.setItem will be keep
2237 * being deferred until the page is quiescent for 2 seconds.
2238 *
2239 * Because localStorage is shared by all pages from the same origin, if multiple
2240 * pages are loaded with different module sets, the possibility exists that
2241 * modules saved by one page will be clobbered by another. The only impact of this
2242 * is minor (merely a less efficient cache use) and the problem would be corrected
2243 * by subsequent page views.
2244 *
2245 * @method
2246 */
2247 update: ( function () {
2248 var timer, hasPendingWrites = false;
2249
2250 function flushWrites() {
2251 var data, key;
2252 if ( !mw.loader.store.enabled ) {
2253 return;
2254 }
2255
2256 mw.loader.store.prune();
2257 key = mw.loader.store.getStoreKey();
2258 try {
2259 // Replacing the content of the module store might fail if the new
2260 // contents would exceed the browser's localStorage size limit. To
2261 // avoid clogging the browser with stale data, always remove the old
2262 // value before attempting to set the new one.
2263 localStorage.removeItem( key );
2264 data = JSON.stringify( mw.loader.store );
2265 localStorage.setItem( key, data );
2266 } catch ( e ) {
2267 mw.trackError( 'resourceloader.exception', {
2268 exception: e,
2269 source: 'store-localstorage-update'
2270 } );
2271 }
2272
2273 hasPendingWrites = false;
2274 }
2275
2276 function request() {
2277 // If another mw.loader.store.set()/update() call happens in the narrow
2278 // time window between requestIdleCallback() and flushWrites firing, ignore it.
2279 // It'll be saved by the already-scheduled flush.
2280 if ( !hasPendingWrites ) {
2281 hasPendingWrites = true;
2282 mw.requestIdleCallback( flushWrites );
2283 }
2284 }
2285
2286 return function () {
2287 // Cancel the previous timer (if it hasn't fired yet)
2288 clearTimeout( timer );
2289 timer = setTimeout( request, 2000 );
2290 };
2291 }() )
2292 }
2293 };
2294 }() ),
2295
2296 // Skeleton user object, extended by the 'mediawiki.user' module.
2297 /**
2298 * @class mw.user
2299 * @singleton
2300 */
2301 user: {
2302 /**
2303 * @property {mw.Map}
2304 */
2305 options: new Map(),
2306 /**
2307 * @property {mw.Map}
2308 */
2309 tokens: new Map()
2310 },
2311
2312 // OOUI widgets specific to MediaWiki
2313 widgets: {}
2314
2315 };
2316
2317 // Attach to window and globally alias
2318 window.mw = window.mediaWiki = mw;
2319 }() );