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