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