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