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