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