Merge "RCFilters: Work around IE11 rendering issues"
[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 rAF = window.requestAnimationFrame || setTimeout;
875
876 function getMarker() {
877 if ( !marker ) {
878 // Cache
879 marker = document.querySelector( 'meta[name="ResourceLoaderDynamicStyles"]' );
880 if ( !marker ) {
881 mw.log( 'Create <meta name="ResourceLoaderDynamicStyles"> dynamically' );
882 marker = $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' )[ 0 ];
883 }
884 }
885 return marker;
886 }
887
888 /**
889 * Create a new style element and add it to the DOM.
890 *
891 * @private
892 * @param {string} text CSS text
893 * @param {Node} [nextNode] The element where the style tag
894 * should be inserted before
895 * @return {HTMLElement} Reference to the created style element
896 */
897 function newStyleTag( text, nextNode ) {
898 var s = document.createElement( 'style' );
899
900 s.appendChild( document.createTextNode( text ) );
901 if ( nextNode && nextNode.parentNode ) {
902 nextNode.parentNode.insertBefore( s, nextNode );
903 } else {
904 document.getElementsByTagName( 'head' )[ 0 ].appendChild( s );
905 }
906
907 return s;
908 }
909
910 /**
911 * Add a bit of CSS text to the current browser page.
912 *
913 * The CSS will be appended to an existing ResourceLoader-created `<style>` tag
914 * or create a new one based on whether the given `cssText` is safe for extension.
915 *
916 * @private
917 * @param {string} [cssText=cssBuffer] If called without cssText,
918 * the internal buffer will be inserted instead.
919 * @param {Function} [callback]
920 */
921 function addEmbeddedCSS( cssText, callback ) {
922 function fireCallbacks() {
923 var oldCallbacks = cssCallbacks;
924 // Reset cssCallbacks variable so it's not polluted by any calls to
925 // addEmbeddedCSS() from one of the callbacks (T105973)
926 cssCallbacks = $.Callbacks();
927 oldCallbacks.fire().empty();
928 }
929
930 if ( callback ) {
931 cssCallbacks.add( callback );
932 }
933
934 // Yield once before creating the <style> tag. This lets multiple stylesheets
935 // accumulate into one buffer, allowing us to reduce how often new stylesheets
936 // are inserted in the browser. Appending a stylesheet and waiting for the
937 // browser to repaint is fairly expensive. (T47810)
938 if ( cssText ) {
939 // Don't extend the buffer if the item needs its own stylesheet.
940 // Keywords like `@import` are only valid at the start of a stylesheet (T37562).
941 if ( !cssBuffer || cssText.slice( 0, '@import'.length ) !== '@import' ) {
942 // Linebreak for somewhat distinguishable sections
943 cssBuffer += '\n' + cssText;
944 if ( !cssBufferTimer ) {
945 cssBufferTimer = rAF( function () {
946 // Wrap in anonymous function that takes no arguments
947 // Support: Firefox < 13
948 // Firefox 12 has non-standard behaviour of passing a number
949 // as first argument to a setTimeout callback.
950 // http://benalman.com/news/2009/07/the-mysterious-firefox-settime/
951 addEmbeddedCSS();
952 } );
953 }
954 return;
955 }
956
957 // This is a scheduled flush for the buffer
958 } else {
959 cssBufferTimer = null;
960 cssText = cssBuffer;
961 cssBuffer = '';
962 }
963
964 $( newStyleTag( cssText, getMarker() ) );
965
966 fireCallbacks();
967 }
968
969 /**
970 * @private
971 * @param {Array} modules List of module names
972 * @return {string} Hash of concatenated version hashes.
973 */
974 function getCombinedVersion( modules ) {
975 var hashes = modules.map( function ( module ) {
976 return registry[ module ].version;
977 } );
978 return fnv132( hashes.join( '' ) );
979 }
980
981 /**
982 * Determine whether all dependencies are in state 'ready', which means we may
983 * execute the module or job now.
984 *
985 * @private
986 * @param {Array} modules Names of modules to be checked
987 * @return {boolean} True if all modules are in state 'ready', false otherwise
988 */
989 function allReady( modules ) {
990 var i;
991 for ( i = 0; i < modules.length; i++ ) {
992 if ( mw.loader.getState( modules[ i ] ) !== 'ready' ) {
993 return false;
994 }
995 }
996 return true;
997 }
998
999 /**
1000 * Determine whether all dependencies are in state 'ready', which means we may
1001 * execute the module or job now.
1002 *
1003 * @private
1004 * @param {Array} modules Names of modules to be checked
1005 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
1006 */
1007 function anyFailed( modules ) {
1008 var i, state;
1009 for ( i = 0; i < modules.length; i++ ) {
1010 state = mw.loader.getState( modules[ i ] );
1011 if ( state === 'error' || state === 'missing' ) {
1012 return true;
1013 }
1014 }
1015 return false;
1016 }
1017
1018 /**
1019 * A module has entered state 'ready', 'error', or 'missing'. Automatically update
1020 * pending jobs and modules that depend upon this module. If the given module failed,
1021 * propagate the 'error' state up the dependency tree. Otherwise, go ahead and execute
1022 * all jobs/modules now having their dependencies satisfied.
1023 *
1024 * Jobs that depend on a failed module, will have their error callback ran (if any).
1025 *
1026 * @private
1027 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
1028 */
1029 function handlePending( module ) {
1030 var j, job, hasErrors, m, stateChange;
1031
1032 if ( registry[ module ].state === 'error' || registry[ module ].state === 'missing' ) {
1033 // If the current module failed, mark all dependent modules also as failed.
1034 // Iterate until steady-state to propagate the error state upwards in the
1035 // dependency tree.
1036 do {
1037 stateChange = false;
1038 for ( m in registry ) {
1039 if ( registry[ m ].state !== 'error' && registry[ m ].state !== 'missing' ) {
1040 if ( anyFailed( registry[ m ].dependencies ) ) {
1041 registry[ m ].state = 'error';
1042 stateChange = true;
1043 }
1044 }
1045 }
1046 } while ( stateChange );
1047 }
1048
1049 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
1050 for ( j = 0; j < jobs.length; j++ ) {
1051 hasErrors = anyFailed( jobs[ j ].dependencies );
1052 if ( hasErrors || allReady( jobs[ j ].dependencies ) ) {
1053 // All dependencies satisfied, or some have errors
1054 job = jobs[ j ];
1055 jobs.splice( j, 1 );
1056 j -= 1;
1057 try {
1058 if ( hasErrors ) {
1059 if ( typeof job.error === 'function' ) {
1060 job.error( new Error( 'Module ' + module + ' has failed dependencies' ), [ module ] );
1061 }
1062 } else {
1063 if ( typeof job.ready === 'function' ) {
1064 job.ready();
1065 }
1066 }
1067 } catch ( e ) {
1068 // A user-defined callback raised an exception.
1069 // Swallow it to protect our state machine!
1070 mw.track( 'resourceloader.exception', { exception: e, module: module, source: 'load-callback' } );
1071 }
1072 }
1073 }
1074
1075 if ( registry[ module ].state === 'ready' ) {
1076 // The current module became 'ready'. Set it in the module store, and recursively execute all
1077 // dependent modules that are loaded and now have all dependencies satisfied.
1078 mw.loader.store.set( module, registry[ module ] );
1079 for ( m in registry ) {
1080 if ( registry[ m ].state === 'loaded' && allReady( registry[ m ].dependencies ) ) {
1081 execute( m );
1082 }
1083 }
1084 }
1085 }
1086
1087 /**
1088 * Resolve dependencies and detect circular references.
1089 *
1090 * @private
1091 * @param {string} module Name of the top-level module whose dependencies shall be
1092 * resolved and sorted.
1093 * @param {Array} resolved Returns a topological sort of the given module and its
1094 * dependencies, such that later modules depend on earlier modules. The array
1095 * contains the module names. If the array contains already some module names,
1096 * this function appends its result to the pre-existing array.
1097 * @param {StringSet} [unresolved] Used to track the current dependency
1098 * chain, and to report loops in the dependency graph.
1099 * @throws {Error} If any unregistered module or a dependency loop is encountered
1100 */
1101 function sortDependencies( module, resolved, unresolved ) {
1102 var i, deps, skip;
1103
1104 if ( !hasOwn.call( registry, module ) ) {
1105 throw new Error( 'Unknown dependency: ' + module );
1106 }
1107
1108 if ( registry[ module ].skip !== null ) {
1109 // eslint-disable-next-line no-new-func
1110 skip = new Function( registry[ module ].skip );
1111 registry[ module ].skip = null;
1112 if ( skip() ) {
1113 registry[ module ].skipped = true;
1114 registry[ module ].dependencies = [];
1115 registry[ module ].state = 'ready';
1116 handlePending( module );
1117 return;
1118 }
1119 }
1120
1121 // Resolves dynamic loader function and replaces it with its own results
1122 if ( typeof registry[ module ].dependencies === 'function' ) {
1123 registry[ module ].dependencies = registry[ module ].dependencies();
1124 // Ensures the module's dependencies are always in an array
1125 if ( typeof registry[ module ].dependencies !== 'object' ) {
1126 registry[ module ].dependencies = [ registry[ module ].dependencies ];
1127 }
1128 }
1129 if ( $.inArray( module, resolved ) !== -1 ) {
1130 // Module already resolved; nothing to do
1131 return;
1132 }
1133 // Create unresolved if not passed in
1134 if ( !unresolved ) {
1135 unresolved = new StringSet();
1136 }
1137 // Tracks down dependencies
1138 deps = registry[ module ].dependencies;
1139 for ( i = 0; i < deps.length; i++ ) {
1140 if ( $.inArray( deps[ i ], resolved ) === -1 ) {
1141 if ( unresolved.has( deps[ i ] ) ) {
1142 throw new Error( mw.format(
1143 'Circular reference detected: $1 -> $2',
1144 module,
1145 deps[ i ]
1146 ) );
1147 }
1148
1149 unresolved.add( module );
1150 sortDependencies( deps[ i ], resolved, unresolved );
1151 }
1152 }
1153 resolved.push( module );
1154 }
1155
1156 /**
1157 * Get names of module that a module depends on, in their proper dependency order.
1158 *
1159 * @private
1160 * @param {string[]} modules Array of string module names
1161 * @return {Array} List of dependencies, including 'module'.
1162 * @throws {Error} If an unregistered module or a dependency loop is encountered
1163 */
1164 function resolve( modules ) {
1165 var i, resolved = [];
1166 for ( i = 0; i < modules.length; i++ ) {
1167 sortDependencies( modules[ i ], resolved );
1168 }
1169 return resolved;
1170 }
1171
1172 /**
1173 * Load and execute a script.
1174 *
1175 * @private
1176 * @param {string} src URL to script, will be used as the src attribute in the script tag
1177 * @return {jQuery.Promise}
1178 */
1179 function addScript( src ) {
1180 return $.ajax( {
1181 url: src,
1182 dataType: 'script',
1183 // Force jQuery behaviour to be for crossDomain. Otherwise jQuery would use
1184 // XHR for a same domain request instead of <script>, which changes the request
1185 // headers (potentially missing a cache hit), and reduces caching in general
1186 // since browsers cache XHR much less (if at all). And XHR means we retrieve
1187 // text, so we'd need to $.globalEval, which then messes up line numbers.
1188 crossDomain: true,
1189 cache: true
1190 } );
1191 }
1192
1193 /**
1194 * Queue the loading and execution of a script for a particular module.
1195 *
1196 * @private
1197 * @param {string} src URL of the script
1198 * @param {string} [moduleName] Name of currently executing module
1199 * @return {jQuery.Promise}
1200 */
1201 function queueModuleScript( src, moduleName ) {
1202 var r = $.Deferred();
1203
1204 pendingRequests.push( function () {
1205 if ( moduleName && hasOwn.call( registry, moduleName ) ) {
1206 // Emulate runScript() part of execute()
1207 window.require = mw.loader.require;
1208 window.module = registry[ moduleName ].module;
1209 }
1210 addScript( src ).always( function () {
1211 // 'module.exports' should not persist after the file is executed to
1212 // avoid leakage to unrelated code. 'require' should be kept, however,
1213 // as asynchronous access to 'require' is allowed and expected. (T144879)
1214 delete window.module;
1215 r.resolve();
1216
1217 // Start the next one (if any)
1218 if ( pendingRequests[ 0 ] ) {
1219 pendingRequests.shift()();
1220 } else {
1221 handlingPendingRequests = false;
1222 }
1223 } );
1224 } );
1225 if ( !handlingPendingRequests && pendingRequests[ 0 ] ) {
1226 handlingPendingRequests = true;
1227 pendingRequests.shift()();
1228 }
1229 return r.promise();
1230 }
1231
1232 /**
1233 * Utility function for execute()
1234 *
1235 * @ignore
1236 * @param {string} [media] Media attribute
1237 * @param {string} url URL
1238 */
1239 function addLink( media, url ) {
1240 var el = document.createElement( 'link' );
1241
1242 el.rel = 'stylesheet';
1243 if ( media && media !== 'all' ) {
1244 el.media = media;
1245 }
1246 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1247 // see #addEmbeddedCSS, T33676, T43331, and T49277 for details.
1248 el.href = url;
1249
1250 $( getMarker() ).before( el );
1251 }
1252
1253 /**
1254 * Executes a loaded module, making it ready to use
1255 *
1256 * @private
1257 * @param {string} module Module name to execute
1258 */
1259 function execute( module ) {
1260 var key, value, media, i, urls, cssHandle, checkCssHandles, runScript,
1261 cssHandlesRegistered = false;
1262
1263 if ( !hasOwn.call( registry, module ) ) {
1264 throw new Error( 'Module has not been registered yet: ' + module );
1265 }
1266 if ( registry[ module ].state !== 'loaded' ) {
1267 throw new Error( 'Module in state "' + registry[ module ].state + '" may not be executed: ' + module );
1268 }
1269
1270 registry[ module ].state = 'executing';
1271
1272 runScript = function () {
1273 var script, markModuleReady, nestedAddScript, legacyWait, implicitDependencies,
1274 // Expand to include dependencies since we have to exclude both legacy modules
1275 // and their dependencies from the legacyWait (to prevent a circular dependency).
1276 legacyModules = resolve( mw.config.get( 'wgResourceLoaderLegacyModules', [] ) );
1277
1278 script = registry[ module ].script;
1279 markModuleReady = function () {
1280 registry[ module ].state = 'ready';
1281 handlePending( module );
1282 };
1283 nestedAddScript = function ( arr, callback, i ) {
1284 // Recursively call queueModuleScript() in its own callback
1285 // for each element of arr.
1286 if ( i >= arr.length ) {
1287 // We're at the end of the array
1288 callback();
1289 return;
1290 }
1291
1292 queueModuleScript( arr[ i ], module ).always( function () {
1293 nestedAddScript( arr, callback, i + 1 );
1294 } );
1295 };
1296
1297 implicitDependencies = ( $.inArray( module, legacyModules ) !== -1 ) ?
1298 [] :
1299 legacyModules;
1300
1301 if ( module === 'user' ) {
1302 // Implicit dependency on the site module. Not real dependency because
1303 // it should run after 'site' regardless of whether it succeeds or fails.
1304 implicitDependencies.push( 'site' );
1305 }
1306
1307 legacyWait = implicitDependencies.length ?
1308 mw.loader.using( implicitDependencies ) :
1309 $.Deferred().resolve();
1310
1311 legacyWait.always( function () {
1312 try {
1313 if ( Array.isArray( script ) ) {
1314 nestedAddScript( script, markModuleReady, 0 );
1315 } else if ( typeof script === 'function' ) {
1316 // Pass jQuery twice so that the signature of the closure which wraps
1317 // the script can bind both '$' and 'jQuery'.
1318 script( $, $, mw.loader.require, registry[ module ].module );
1319 markModuleReady();
1320
1321 } else if ( typeof script === 'string' ) {
1322 // Site and user modules are legacy scripts that run in the global scope.
1323 // This is transported as a string instead of a function to avoid needing
1324 // to use string manipulation to undo the function wrapper.
1325 $.globalEval( script );
1326 markModuleReady();
1327
1328 } else {
1329 // Module without script
1330 markModuleReady();
1331 }
1332 } catch ( e ) {
1333 // Use mw.track instead of mw.log because these errors are common in production mode
1334 // (e.g. undefined variable), and mw.log is only enabled in debug mode.
1335 registry[ module ].state = 'error';
1336 mw.track( 'resourceloader.exception', { exception: e, module: module, source: 'module-execute' } );
1337 handlePending( module );
1338 }
1339 } );
1340 };
1341
1342 // Add localizations to message system
1343 if ( registry[ module ].messages ) {
1344 mw.messages.set( registry[ module ].messages );
1345 }
1346
1347 // Initialise templates
1348 if ( registry[ module ].templates ) {
1349 mw.templates.set( module, registry[ module ].templates );
1350 }
1351
1352 // Make sure we don't run the scripts until all stylesheet insertions have completed.
1353 ( function () {
1354 var pending = 0;
1355 checkCssHandles = function () {
1356 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
1357 // one of the cssHandles is fired while we're still creating more handles.
1358 if ( cssHandlesRegistered && pending === 0 && runScript ) {
1359 runScript();
1360 runScript = undefined; // Revoke
1361 }
1362 };
1363 cssHandle = function () {
1364 var check = checkCssHandles;
1365 pending++;
1366 return function () {
1367 if ( check ) {
1368 pending--;
1369 check();
1370 check = undefined; // Revoke
1371 }
1372 };
1373 };
1374 }() );
1375
1376 // Process styles (see also mw.loader.implement)
1377 // * back-compat: { <media>: css }
1378 // * back-compat: { <media>: [url, ..] }
1379 // * { "css": [css, ..] }
1380 // * { "url": { <media>: [url, ..] } }
1381 if ( registry[ module ].style ) {
1382 for ( key in registry[ module ].style ) {
1383 value = registry[ module ].style[ key ];
1384 media = undefined;
1385
1386 if ( key !== 'url' && key !== 'css' ) {
1387 // Backwards compatibility, key is a media-type
1388 if ( typeof value === 'string' ) {
1389 // back-compat: { <media>: css }
1390 // Ignore 'media' because it isn't supported (nor was it used).
1391 // Strings are pre-wrapped in "@media". The media-type was just ""
1392 // (because it had to be set to something).
1393 // This is one of the reasons why this format is no longer used.
1394 addEmbeddedCSS( value, cssHandle() );
1395 } else {
1396 // back-compat: { <media>: [url, ..] }
1397 media = key;
1398 key = 'bc-url';
1399 }
1400 }
1401
1402 // Array of css strings in key 'css',
1403 // or back-compat array of urls from media-type
1404 if ( Array.isArray( value ) ) {
1405 for ( i = 0; i < value.length; i++ ) {
1406 if ( key === 'bc-url' ) {
1407 // back-compat: { <media>: [url, ..] }
1408 addLink( media, value[ i ] );
1409 } else if ( key === 'css' ) {
1410 // { "css": [css, ..] }
1411 addEmbeddedCSS( value[ i ], cssHandle() );
1412 }
1413 }
1414 // Not an array, but a regular object
1415 // Array of urls inside media-type key
1416 } else if ( typeof value === 'object' ) {
1417 // { "url": { <media>: [url, ..] } }
1418 for ( media in value ) {
1419 urls = value[ media ];
1420 for ( i = 0; i < urls.length; i++ ) {
1421 addLink( media, urls[ i ] );
1422 }
1423 }
1424 }
1425 }
1426 }
1427
1428 // Kick off.
1429 cssHandlesRegistered = true;
1430 checkCssHandles();
1431 }
1432
1433 /**
1434 * Add one or more modules to the module load queue.
1435 *
1436 * See also #work().
1437 *
1438 * @private
1439 * @param {string|string[]} dependencies Module name or array of string module names
1440 * @param {Function} [ready] Callback to execute when all dependencies are ready
1441 * @param {Function} [error] Callback to execute when any dependency fails
1442 */
1443 function enqueue( dependencies, ready, error ) {
1444 // Allow calling by single module name
1445 if ( typeof dependencies === 'string' ) {
1446 dependencies = [ dependencies ];
1447 }
1448
1449 // Add ready and error callbacks if they were given
1450 if ( ready !== undefined || error !== undefined ) {
1451 jobs.push( {
1452 // Narrow down the list to modules that are worth waiting for
1453 dependencies: $.grep( dependencies, function ( module ) {
1454 var state = mw.loader.getState( module );
1455 return state === 'registered' || state === 'loaded' || state === 'loading' || state === 'executing';
1456 } ),
1457 ready: ready,
1458 error: error
1459 } );
1460 }
1461
1462 $.each( dependencies, function ( idx, module ) {
1463 var state = mw.loader.getState( module );
1464 // Only queue modules that are still in the initial 'registered' state
1465 // (not ones already loading, ready or error).
1466 if ( state === 'registered' && $.inArray( module, queue ) === -1 ) {
1467 // Private modules must be embedded in the page. Don't bother queuing
1468 // these as the server will deny them anyway (T101806).
1469 if ( registry[ module ].group === 'private' ) {
1470 registry[ module ].state = 'error';
1471 handlePending( module );
1472 return;
1473 }
1474 queue.push( module );
1475 }
1476 } );
1477
1478 mw.loader.work();
1479 }
1480
1481 function sortQuery( o ) {
1482 var key,
1483 sorted = {},
1484 a = [];
1485
1486 for ( key in o ) {
1487 if ( hasOwn.call( o, key ) ) {
1488 a.push( key );
1489 }
1490 }
1491 a.sort();
1492 for ( key = 0; key < a.length; key++ ) {
1493 sorted[ a[ key ] ] = o[ a[ key ] ];
1494 }
1495 return sorted;
1496 }
1497
1498 /**
1499 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
1500 * to a query string of the form foo.bar,baz|bar.baz,quux
1501 *
1502 * @private
1503 * @param {Object} moduleMap Module map
1504 * @return {string} Module query string
1505 */
1506 function buildModulesString( moduleMap ) {
1507 var p, prefix,
1508 arr = [];
1509
1510 for ( prefix in moduleMap ) {
1511 p = prefix === '' ? '' : prefix + '.';
1512 arr.push( p + moduleMap[ prefix ].join( ',' ) );
1513 }
1514 return arr.join( '|' );
1515 }
1516
1517 /**
1518 * Make a network request to load modules from the server.
1519 *
1520 * @private
1521 * @param {Object} moduleMap Module map, see #buildModulesString
1522 * @param {Object} currReqBase Object with other parameters (other than 'modules') to use in the request
1523 * @param {string} sourceLoadScript URL of load.php
1524 */
1525 function doRequest( moduleMap, currReqBase, sourceLoadScript ) {
1526 var query = $.extend(
1527 { modules: buildModulesString( moduleMap ) },
1528 currReqBase
1529 );
1530 query = sortQuery( query );
1531 addScript( sourceLoadScript + '?' + $.param( query ) );
1532 }
1533
1534 /**
1535 * Resolve indexed dependencies.
1536 *
1537 * ResourceLoader uses an optimization to save space which replaces module names in
1538 * dependency lists with the index of that module within the array of module
1539 * registration data if it exists. The benefit is a significant reduction in the data
1540 * size of the startup module. This function changes those dependency lists back to
1541 * arrays of strings.
1542 *
1543 * @private
1544 * @param {Array} modules Modules array
1545 */
1546 function resolveIndexedDependencies( modules ) {
1547 var i, j, deps;
1548 function resolveIndex( dep ) {
1549 return typeof dep === 'number' ? modules[ dep ][ 0 ] : dep;
1550 }
1551 for ( i = 0; i < modules.length; i++ ) {
1552 deps = modules[ i ][ 2 ];
1553 if ( deps ) {
1554 for ( j = 0; j < deps.length; j++ ) {
1555 deps[ j ] = resolveIndex( deps[ j ] );
1556 }
1557 }
1558 }
1559 }
1560
1561 /**
1562 * Create network requests for a batch of modules.
1563 *
1564 * This is an internal method for #work(). This must not be called directly
1565 * unless the modules are already registered, and no request is in progress,
1566 * and the module state has already been set to `loading`.
1567 *
1568 * @private
1569 * @param {string[]} batch
1570 */
1571 function batchRequest( batch ) {
1572 var reqBase, splits, maxQueryLength, b, bSource, bGroup, bSourceGroup,
1573 source, group, i, modules, sourceLoadScript,
1574 currReqBase, currReqBaseLength, moduleMap, l,
1575 lastDotIndex, prefix, suffix, bytesAdded;
1576
1577 if ( !batch.length ) {
1578 return;
1579 }
1580
1581 // Always order modules alphabetically to help reduce cache
1582 // misses for otherwise identical content.
1583 batch.sort();
1584
1585 // Build a list of query parameters common to all requests
1586 reqBase = {
1587 skin: mw.config.get( 'skin' ),
1588 lang: mw.config.get( 'wgUserLanguage' ),
1589 debug: mw.config.get( 'debug' )
1590 };
1591 maxQueryLength = mw.config.get( 'wgResourceLoaderMaxQueryLength', 2000 );
1592
1593 // Split module list by source and by group.
1594 splits = {};
1595 for ( b = 0; b < batch.length; b++ ) {
1596 bSource = registry[ batch[ b ] ].source;
1597 bGroup = registry[ batch[ b ] ].group;
1598 if ( !hasOwn.call( splits, bSource ) ) {
1599 splits[ bSource ] = {};
1600 }
1601 if ( !hasOwn.call( splits[ bSource ], bGroup ) ) {
1602 splits[ bSource ][ bGroup ] = [];
1603 }
1604 bSourceGroup = splits[ bSource ][ bGroup ];
1605 bSourceGroup.push( batch[ b ] );
1606 }
1607
1608 for ( source in splits ) {
1609
1610 sourceLoadScript = sources[ source ];
1611
1612 for ( group in splits[ source ] ) {
1613
1614 // Cache access to currently selected list of
1615 // modules for this group from this source.
1616 modules = splits[ source ][ group ];
1617
1618 currReqBase = $.extend( {
1619 version: getCombinedVersion( modules )
1620 }, reqBase );
1621 // For user modules append a user name to the query string.
1622 if ( group === 'user' && mw.config.get( 'wgUserName' ) !== null ) {
1623 currReqBase.user = mw.config.get( 'wgUserName' );
1624 }
1625 currReqBaseLength = $.param( currReqBase ).length;
1626 // We may need to split up the request to honor the query string length limit,
1627 // so build it piece by piece.
1628 l = currReqBaseLength + 9; // '&modules='.length == 9
1629
1630 moduleMap = {}; // { prefix: [ suffixes ] }
1631
1632 for ( i = 0; i < modules.length; i++ ) {
1633 // Determine how many bytes this module would add to the query string
1634 lastDotIndex = modules[ i ].lastIndexOf( '.' );
1635
1636 // If lastDotIndex is -1, substr() returns an empty string
1637 prefix = modules[ i ].substr( 0, lastDotIndex );
1638 suffix = modules[ i ].slice( lastDotIndex + 1 );
1639
1640 bytesAdded = hasOwn.call( moduleMap, prefix ) ?
1641 suffix.length + 3 : // '%2C'.length == 3
1642 modules[ i ].length + 3; // '%7C'.length == 3
1643
1644 // If the url would become too long, create a new one,
1645 // but don't create empty requests
1646 if ( maxQueryLength > 0 && !$.isEmptyObject( moduleMap ) && l + bytesAdded > maxQueryLength ) {
1647 // This url would become too long, create a new one, and start the old one
1648 doRequest( moduleMap, currReqBase, sourceLoadScript );
1649 moduleMap = {};
1650 l = currReqBaseLength + 9;
1651 mw.track( 'resourceloader.splitRequest', { maxQueryLength: maxQueryLength } );
1652 }
1653 if ( !hasOwn.call( moduleMap, prefix ) ) {
1654 moduleMap[ prefix ] = [];
1655 }
1656 moduleMap[ prefix ].push( suffix );
1657 l += bytesAdded;
1658 }
1659 // If there's anything left in moduleMap, request that too
1660 if ( !$.isEmptyObject( moduleMap ) ) {
1661 doRequest( moduleMap, currReqBase, sourceLoadScript );
1662 }
1663 }
1664 }
1665 }
1666
1667 /**
1668 * @private
1669 * @param {string[]} implementations Array containing pieces of JavaScript code in the
1670 * form of calls to mw.loader#implement().
1671 * @param {Function} cb Callback in case of failure
1672 * @param {Error} cb.err
1673 */
1674 function asyncEval( implementations, cb ) {
1675 if ( !implementations.length ) {
1676 return;
1677 }
1678 mw.requestIdleCallback( function () {
1679 try {
1680 $.globalEval( implementations.join( ';' ) );
1681 } catch ( err ) {
1682 cb( err );
1683 }
1684 } );
1685 }
1686
1687 /**
1688 * Make a versioned key for a specific module.
1689 *
1690 * @private
1691 * @param {string} module Module name
1692 * @return {string|null} Module key in format '`[name]@[version]`',
1693 * or null if the module does not exist
1694 */
1695 function getModuleKey( module ) {
1696 return hasOwn.call( registry, module ) ?
1697 ( module + '@' + registry[ module ].version ) : null;
1698 }
1699
1700 /**
1701 * @private
1702 * @param {string} key Module name or '`[name]@[version]`'
1703 * @return {Object}
1704 */
1705 function splitModuleKey( key ) {
1706 var index = key.indexOf( '@' );
1707 if ( index === -1 ) {
1708 return { name: key };
1709 }
1710 return {
1711 name: key.slice( 0, index ),
1712 version: key.slice( index + 1 )
1713 };
1714 }
1715
1716 /* Public Members */
1717 return {
1718 /**
1719 * The module registry is exposed as an aid for debugging and inspecting page
1720 * state; it is not a public interface for modifying the registry.
1721 *
1722 * @see #registry
1723 * @property
1724 * @private
1725 */
1726 moduleRegistry: registry,
1727
1728 /**
1729 * @inheritdoc #newStyleTag
1730 * @method
1731 */
1732 addStyleTag: newStyleTag,
1733
1734 /**
1735 * Start loading of all queued module dependencies.
1736 *
1737 * @protected
1738 */
1739 work: function () {
1740 var q, batch, implementations, sourceModules;
1741
1742 batch = [];
1743
1744 // Appends a list of modules from the queue to the batch
1745 for ( q = 0; q < queue.length; q++ ) {
1746 // Only load modules which are registered
1747 if ( hasOwn.call( registry, queue[ q ] ) && registry[ queue[ q ] ].state === 'registered' ) {
1748 // Prevent duplicate entries
1749 if ( $.inArray( queue[ q ], batch ) === -1 ) {
1750 batch.push( queue[ q ] );
1751 // Mark registered modules as loading
1752 registry[ queue[ q ] ].state = 'loading';
1753 }
1754 }
1755 }
1756
1757 // Now that the queue has been processed into a batch, clear the queue.
1758 // This MUST happen before we initiate any eval or network request. Otherwise,
1759 // it is possible for a cached script to instantly trigger the same work queue
1760 // again; all before we've cleared it causing each request to include modules
1761 // which are already loaded.
1762 queue = [];
1763
1764 if ( !batch.length ) {
1765 return;
1766 }
1767
1768 mw.loader.store.init();
1769 if ( mw.loader.store.enabled ) {
1770 implementations = [];
1771 sourceModules = [];
1772 batch = $.grep( batch, function ( module ) {
1773 var implementation = mw.loader.store.get( module );
1774 if ( implementation ) {
1775 implementations.push( implementation );
1776 sourceModules.push( module );
1777 return false;
1778 }
1779 return true;
1780 } );
1781 asyncEval( implementations, function ( err ) {
1782 var failed;
1783 // Not good, the cached mw.loader.implement calls failed! This should
1784 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1785 // Depending on how corrupt the string is, it is likely that some
1786 // modules' implement() succeeded while the ones after the error will
1787 // never run and leave their modules in the 'loading' state forever.
1788 mw.loader.store.stats.failed++;
1789
1790 // Since this is an error not caused by an individual module but by
1791 // something that infected the implement call itself, don't take any
1792 // risks and clear everything in this cache.
1793 mw.loader.store.clear();
1794
1795 mw.track( 'resourceloader.exception', { exception: err, source: 'store-eval' } );
1796 // Re-add the failed ones that are still pending back to the batch
1797 failed = $.grep( sourceModules, function ( module ) {
1798 return registry[ module ].state === 'loading';
1799 } );
1800 batchRequest( failed );
1801 } );
1802 }
1803
1804 batchRequest( batch );
1805 },
1806
1807 /**
1808 * Register a source.
1809 *
1810 * The #work() method will use this information to split up requests by source.
1811 *
1812 * mw.loader.addSource( 'mediawikiwiki', '//www.mediawiki.org/w/load.php' );
1813 *
1814 * @param {string|Object} id Source ID, or object mapping ids to load urls
1815 * @param {string} loadUrl Url to a load.php end point
1816 * @throws {Error} If source id is already registered
1817 */
1818 addSource: function ( id, loadUrl ) {
1819 var source;
1820 // Allow multiple additions
1821 if ( typeof id === 'object' ) {
1822 for ( source in id ) {
1823 mw.loader.addSource( source, id[ source ] );
1824 }
1825 return;
1826 }
1827
1828 if ( hasOwn.call( sources, id ) ) {
1829 throw new Error( 'source already registered: ' + id );
1830 }
1831
1832 sources[ id ] = loadUrl;
1833 },
1834
1835 /**
1836 * Register a module, letting the system know about it and its properties.
1837 *
1838 * The startup modules contain calls to this method.
1839 *
1840 * When using multiple module registration by passing an array, dependencies that
1841 * are specified as references to modules within the array will be resolved before
1842 * the modules are registered.
1843 *
1844 * @param {string|Array} module Module name or array of arrays, each containing
1845 * a list of arguments compatible with this method
1846 * @param {string|number} version Module version hash (falls backs to empty string)
1847 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1848 * @param {string|Array|Function} dependencies One string or array of strings of module
1849 * names on which this module depends, or a function that returns that array.
1850 * @param {string} [group=null] Group which the module is in
1851 * @param {string} [source='local'] Name of the source
1852 * @param {string} [skip=null] Script body of the skip function
1853 */
1854 register: function ( module, version, dependencies, group, source, skip ) {
1855 var i, deps;
1856 // Allow multiple registration
1857 if ( typeof module === 'object' ) {
1858 resolveIndexedDependencies( module );
1859 for ( i = 0; i < module.length; i++ ) {
1860 // module is an array of module names
1861 if ( typeof module[ i ] === 'string' ) {
1862 mw.loader.register( module[ i ] );
1863 // module is an array of arrays
1864 } else if ( typeof module[ i ] === 'object' ) {
1865 mw.loader.register.apply( mw.loader, module[ i ] );
1866 }
1867 }
1868 return;
1869 }
1870 if ( hasOwn.call( registry, module ) ) {
1871 throw new Error( 'module already registered: ' + module );
1872 }
1873 if ( typeof dependencies === 'string' ) {
1874 // A single module name
1875 deps = [ dependencies ];
1876 } else if ( typeof dependencies === 'object' || typeof dependencies === 'function' ) {
1877 // Array of module names or a function that returns an array
1878 deps = dependencies;
1879 }
1880 // List the module as registered
1881 registry[ module ] = {
1882 // Exposed to execute() for mw.loader.implement() closures.
1883 // Import happens via require().
1884 module: {
1885 exports: {}
1886 },
1887 version: version !== undefined ? String( version ) : '',
1888 dependencies: deps || [],
1889 group: typeof group === 'string' ? group : null,
1890 source: typeof source === 'string' ? source : 'local',
1891 state: 'registered',
1892 skip: typeof skip === 'string' ? skip : null
1893 };
1894 },
1895
1896 /**
1897 * Implement a module given the components that make up the module.
1898 *
1899 * When #load() or #using() requests one or more modules, the server
1900 * response contain calls to this function.
1901 *
1902 * @param {string} module Name of module and current module version. Formatted
1903 * as '`[name]@[version]`". This version should match the requested version
1904 * (from #batchRequest and #registry). This avoids race conditions (T117587).
1905 * For back-compat with MediaWiki 1.27 and earlier, the version may be omitted.
1906 * @param {Function|Array|string} [script] Function with module code, list of URLs
1907 * to load via `<script src>`, or string of module code for `$.globalEval()`.
1908 * @param {Object} [style] Should follow one of the following patterns:
1909 *
1910 * { "css": [css, ..] }
1911 * { "url": { <media>: [url, ..] } }
1912 *
1913 * And for backwards compatibility (needs to be supported forever due to caching):
1914 *
1915 * { <media>: css }
1916 * { <media>: [url, ..] }
1917 *
1918 * The reason css strings are not concatenated anymore is T33676. We now check
1919 * whether it's safe to extend the stylesheet.
1920 *
1921 * @protected
1922 * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1923 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1924 */
1925 implement: function ( module, script, style, messages, templates ) {
1926 var split = splitModuleKey( module ),
1927 name = split.name,
1928 version = split.version;
1929 // Automatically register module
1930 if ( !hasOwn.call( registry, name ) ) {
1931 mw.loader.register( name );
1932 }
1933 // Check for duplicate implementation
1934 if ( hasOwn.call( registry, name ) && registry[ name ].script !== undefined ) {
1935 throw new Error( 'module already implemented: ' + name );
1936 }
1937 if ( version ) {
1938 // Without this reset, if there is a version mismatch between the
1939 // requested and received module version, then mw.loader.store would
1940 // cache the response under the requested key. Thus poisoning the cache
1941 // indefinitely with a stale value. (T117587)
1942 registry[ name ].version = version;
1943 }
1944 // Attach components
1945 registry[ name ].script = script || null;
1946 registry[ name ].style = style || null;
1947 registry[ name ].messages = messages || null;
1948 registry[ name ].templates = templates || null;
1949 // The module may already have been marked as erroneous
1950 if ( $.inArray( registry[ name ].state, [ 'error', 'missing' ] ) === -1 ) {
1951 registry[ name ].state = 'loaded';
1952 if ( allReady( registry[ name ].dependencies ) ) {
1953 execute( name );
1954 }
1955 }
1956 },
1957
1958 /**
1959 * Execute a function as soon as one or more required modules are ready.
1960 *
1961 * Example of inline dependency on OOjs:
1962 *
1963 * mw.loader.using( 'oojs', function () {
1964 * OO.compare( [ 1 ], [ 1 ] );
1965 * } );
1966 *
1967 * Since MediaWiki 1.23 this also returns a promise.
1968 *
1969 * Since MediaWiki 1.28 the promise is resolved with a `require` function.
1970 *
1971 * @param {string|Array} dependencies Module name or array of modules names the
1972 * callback depends on to be ready before executing
1973 * @param {Function} [ready] Callback to execute when all dependencies are ready
1974 * @param {Function} [error] Callback to execute if one or more dependencies failed
1975 * @return {jQuery.Promise} With a `require` function
1976 */
1977 using: function ( dependencies, ready, error ) {
1978 var deferred = $.Deferred();
1979
1980 // Allow calling with a single dependency as a string
1981 if ( typeof dependencies === 'string' ) {
1982 dependencies = [ dependencies ];
1983 }
1984
1985 if ( ready ) {
1986 deferred.done( ready );
1987 }
1988 if ( error ) {
1989 deferred.fail( error );
1990 }
1991
1992 try {
1993 // Resolve entire dependency map
1994 dependencies = resolve( dependencies );
1995 } catch ( e ) {
1996 return deferred.reject( e ).promise();
1997 }
1998 if ( allReady( dependencies ) ) {
1999 // Run ready immediately
2000 deferred.resolve( mw.loader.require );
2001 } else if ( anyFailed( dependencies ) ) {
2002 // Execute error immediately if any dependencies have errors
2003 deferred.reject(
2004 new Error( 'One or more dependencies failed to load' ),
2005 dependencies
2006 );
2007 } else {
2008 // Not all dependencies are ready, add to the load queue
2009 enqueue( dependencies, function () {
2010 deferred.resolve( mw.loader.require );
2011 }, deferred.reject );
2012 }
2013
2014 return deferred.promise();
2015 },
2016
2017 /**
2018 * Load an external script or one or more modules.
2019 *
2020 * @param {string|Array} modules Either the name of a module, array of modules,
2021 * or a URL of an external script or style
2022 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
2023 * external script or style; acceptable values are "text/css" and
2024 * "text/javascript"; if no type is provided, text/javascript is assumed.
2025 */
2026 load: function ( modules, type ) {
2027 var filtered, l;
2028
2029 // Allow calling with a url or single dependency as a string
2030 if ( typeof modules === 'string' ) {
2031 // "https://example.org/x.js", "http://example.org/x.js", "//example.org/x.js", "/x.js"
2032 if ( /^(https?:)?\/?\//.test( modules ) ) {
2033 if ( type === 'text/css' ) {
2034 l = document.createElement( 'link' );
2035 l.rel = 'stylesheet';
2036 l.href = modules;
2037 $( 'head' ).append( l );
2038 return;
2039 }
2040 if ( type === 'text/javascript' || type === undefined ) {
2041 addScript( modules );
2042 return;
2043 }
2044 // Unknown type
2045 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type );
2046 }
2047 // Called with single module
2048 modules = [ modules ];
2049 }
2050
2051 // Filter out undefined modules, otherwise resolve() will throw
2052 // an exception for trying to load an undefined module.
2053 // Undefined modules are acceptable here in load(), because load() takes
2054 // an array of unrelated modules, whereas the modules passed to
2055 // using() are related and must all be loaded.
2056 filtered = $.grep( modules, function ( module ) {
2057 var state = mw.loader.getState( module );
2058 return state !== null && state !== 'error' && state !== 'missing';
2059 } );
2060
2061 if ( filtered.length === 0 ) {
2062 return;
2063 }
2064 // Resolve entire dependency map
2065 filtered = resolve( filtered );
2066 // If all modules are ready, or if any modules have errors, nothing to be done.
2067 if ( allReady( filtered ) || anyFailed( filtered ) ) {
2068 return;
2069 }
2070 // Some modules are not yet ready, add to module load queue.
2071 enqueue( filtered, undefined, undefined );
2072 },
2073
2074 /**
2075 * Change the state of one or more modules.
2076 *
2077 * @param {string|Object} module Module name or object of module name/state pairs
2078 * @param {string} state State name
2079 */
2080 state: function ( module, state ) {
2081 var m;
2082
2083 if ( typeof module === 'object' ) {
2084 for ( m in module ) {
2085 mw.loader.state( m, module[ m ] );
2086 }
2087 return;
2088 }
2089 if ( !hasOwn.call( registry, module ) ) {
2090 mw.loader.register( module );
2091 }
2092 registry[ module ].state = state;
2093 if ( $.inArray( state, [ 'ready', 'error', 'missing' ] ) !== -1 ) {
2094 // Make sure pending modules depending on this one get executed if their
2095 // dependencies are now fulfilled!
2096 handlePending( module );
2097 }
2098 },
2099
2100 /**
2101 * Get the version of a module.
2102 *
2103 * @param {string} module Name of module
2104 * @return {string|null} The version, or null if the module (or its version) is not
2105 * in the registry.
2106 */
2107 getVersion: function ( module ) {
2108 if ( !hasOwn.call( registry, module ) || registry[ module ].version === undefined ) {
2109 return null;
2110 }
2111 return registry[ module ].version;
2112 },
2113
2114 /**
2115 * Get the state of a module.
2116 *
2117 * @param {string} module Name of module
2118 * @return {string|null} The state, or null if the module (or its state) is not
2119 * in the registry.
2120 */
2121 getState: function ( module ) {
2122 if ( !hasOwn.call( registry, module ) || registry[ module ].state === undefined ) {
2123 return null;
2124 }
2125 return registry[ module ].state;
2126 },
2127
2128 /**
2129 * Get the names of all registered modules.
2130 *
2131 * @return {Array}
2132 */
2133 getModuleNames: function () {
2134 return Object.keys( registry );
2135 },
2136
2137 /**
2138 * Get the exported value of a module.
2139 *
2140 * Modules may provide this via their local `module.exports`.
2141 *
2142 * @protected
2143 * @since 1.27
2144 * @param {string} moduleName Module name
2145 * @return {Mixed} Exported value
2146 */
2147 require: function ( moduleName ) {
2148 var state = mw.loader.getState( moduleName );
2149
2150 // Only ready modules can be required
2151 if ( state !== 'ready' ) {
2152 // Module may've forgotten to declare a dependency
2153 throw new Error( 'Module "' + moduleName + '" is not loaded.' );
2154 }
2155
2156 return registry[ moduleName ].module.exports;
2157 },
2158
2159 /**
2160 * @inheritdoc mw.inspect#runReports
2161 * @method
2162 */
2163 inspect: function () {
2164 var args = slice.call( arguments );
2165 mw.loader.using( 'mediawiki.inspect', function () {
2166 mw.inspect.runReports.apply( mw.inspect, args );
2167 } );
2168 },
2169
2170 /**
2171 * On browsers that implement the localStorage API, the module store serves as a
2172 * smart complement to the browser cache. Unlike the browser cache, the module store
2173 * can slice a concatenated response from ResourceLoader into its constituent
2174 * modules and cache each of them separately, using each module's versioning scheme
2175 * to determine when the cache should be invalidated.
2176 *
2177 * @singleton
2178 * @class mw.loader.store
2179 */
2180 store: {
2181 // Whether the store is in use on this page.
2182 enabled: null,
2183
2184 // Modules whose string representation exceeds 100 kB are
2185 // ineligible for storage. See bug T66721.
2186 MODULE_SIZE_MAX: 100 * 1000,
2187
2188 // The contents of the store, mapping '[name]@[version]' keys
2189 // to module implementations.
2190 items: {},
2191
2192 // Cache hit stats
2193 stats: { hits: 0, misses: 0, expired: 0, failed: 0 },
2194
2195 /**
2196 * Construct a JSON-serializable object representing the content of the store.
2197 *
2198 * @return {Object} Module store contents.
2199 */
2200 toJSON: function () {
2201 return { items: mw.loader.store.items, vary: mw.loader.store.getVary() };
2202 },
2203
2204 /**
2205 * Get the localStorage key for the entire module store. The key references
2206 * $wgDBname to prevent clashes between wikis which share a common host.
2207 *
2208 * @return {string} localStorage item key
2209 */
2210 getStoreKey: function () {
2211 return 'MediaWikiModuleStore:' + mw.config.get( 'wgDBname' );
2212 },
2213
2214 /**
2215 * Get a key on which to vary the module cache.
2216 *
2217 * @return {string} String of concatenated vary conditions.
2218 */
2219 getVary: function () {
2220 return [
2221 mw.config.get( 'skin' ),
2222 mw.config.get( 'wgResourceLoaderStorageVersion' ),
2223 mw.config.get( 'wgUserLanguage' )
2224 ].join( ':' );
2225 },
2226
2227 /**
2228 * Initialize the store.
2229 *
2230 * Retrieves store from localStorage and (if successfully retrieved) decoding
2231 * the stored JSON value to a plain object.
2232 *
2233 * The try / catch block is used for JSON & localStorage feature detection.
2234 * See the in-line documentation for Modernizr's localStorage feature detection
2235 * code for a full account of why we need a try / catch:
2236 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2237 */
2238 init: function () {
2239 var raw, data;
2240
2241 if ( mw.loader.store.enabled !== null ) {
2242 // Init already ran
2243 return;
2244 }
2245
2246 if (
2247 // Disabled because localStorage quotas are tight and (in Firefox's case)
2248 // shared by multiple origins.
2249 // See T66721, and <https://bugzilla.mozilla.org/show_bug.cgi?id=1064466>.
2250 /Firefox|Opera/.test( navigator.userAgent ) ||
2251
2252 // Disabled by configuration.
2253 !mw.config.get( 'wgResourceLoaderStorageEnabled' )
2254 ) {
2255 // Clear any previous store to free up space. (T66721)
2256 mw.loader.store.clear();
2257 mw.loader.store.enabled = false;
2258 return;
2259 }
2260 if ( mw.config.get( 'debug' ) ) {
2261 // Disable module store in debug mode
2262 mw.loader.store.enabled = false;
2263 return;
2264 }
2265
2266 try {
2267 raw = localStorage.getItem( mw.loader.store.getStoreKey() );
2268 // If we get here, localStorage is available; mark enabled
2269 mw.loader.store.enabled = true;
2270 data = JSON.parse( raw );
2271 if ( data && typeof data.items === 'object' && data.vary === mw.loader.store.getVary() ) {
2272 mw.loader.store.items = data.items;
2273 return;
2274 }
2275 } catch ( e ) {
2276 mw.track( 'resourceloader.exception', { exception: e, source: 'store-localstorage-init' } );
2277 }
2278
2279 if ( raw === undefined ) {
2280 // localStorage failed; disable store
2281 mw.loader.store.enabled = false;
2282 } else {
2283 mw.loader.store.update();
2284 }
2285 },
2286
2287 /**
2288 * Retrieve a module from the store and update cache hit stats.
2289 *
2290 * @param {string} module Module name
2291 * @return {string|boolean} Module implementation or false if unavailable
2292 */
2293 get: function ( module ) {
2294 var key;
2295
2296 if ( !mw.loader.store.enabled ) {
2297 return false;
2298 }
2299
2300 key = getModuleKey( module );
2301 if ( key in mw.loader.store.items ) {
2302 mw.loader.store.stats.hits++;
2303 return mw.loader.store.items[ key ];
2304 }
2305 mw.loader.store.stats.misses++;
2306 return false;
2307 },
2308
2309 /**
2310 * Stringify a module and queue it for storage.
2311 *
2312 * @param {string} module Module name
2313 * @param {Object} descriptor The module's descriptor as set in the registry
2314 * @return {boolean} Module was set
2315 */
2316 set: function ( module, descriptor ) {
2317 var args, key, src;
2318
2319 if ( !mw.loader.store.enabled ) {
2320 return false;
2321 }
2322
2323 key = getModuleKey( module );
2324
2325 if (
2326 // Already stored a copy of this exact version
2327 key in mw.loader.store.items ||
2328 // Module failed to load
2329 descriptor.state !== 'ready' ||
2330 // Unversioned, private, or site-/user-specific
2331 ( !descriptor.version || $.inArray( descriptor.group, [ 'private', 'user' ] ) !== -1 ) ||
2332 // Partial descriptor
2333 // (e.g. skipped module, or style module with state=ready)
2334 $.inArray( undefined, [ descriptor.script, descriptor.style,
2335 descriptor.messages, descriptor.templates ] ) !== -1
2336 ) {
2337 // Decline to store
2338 return false;
2339 }
2340
2341 try {
2342 args = [
2343 JSON.stringify( key ),
2344 typeof descriptor.script === 'function' ?
2345 String( descriptor.script ) :
2346 JSON.stringify( descriptor.script ),
2347 JSON.stringify( descriptor.style ),
2348 JSON.stringify( descriptor.messages ),
2349 JSON.stringify( descriptor.templates )
2350 ];
2351 // Attempted workaround for a possible Opera bug (bug T59567).
2352 // This regex should never match under sane conditions.
2353 if ( /^\s*\(/.test( args[ 1 ] ) ) {
2354 args[ 1 ] = 'function' + args[ 1 ];
2355 mw.track( 'resourceloader.assert', { source: 'bug-T59567' } );
2356 }
2357 } catch ( e ) {
2358 mw.track( 'resourceloader.exception', { exception: e, source: 'store-localstorage-json' } );
2359 return false;
2360 }
2361
2362 src = 'mw.loader.implement(' + args.join( ',' ) + ');';
2363 if ( src.length > mw.loader.store.MODULE_SIZE_MAX ) {
2364 return false;
2365 }
2366 mw.loader.store.items[ key ] = src;
2367 mw.loader.store.update();
2368 return true;
2369 },
2370
2371 /**
2372 * Iterate through the module store, removing any item that does not correspond
2373 * (in name and version) to an item in the module registry.
2374 *
2375 * @return {boolean} Store was pruned
2376 */
2377 prune: function () {
2378 var key, module;
2379
2380 if ( !mw.loader.store.enabled ) {
2381 return false;
2382 }
2383
2384 for ( key in mw.loader.store.items ) {
2385 module = key.slice( 0, key.indexOf( '@' ) );
2386 if ( getModuleKey( module ) !== key ) {
2387 mw.loader.store.stats.expired++;
2388 delete mw.loader.store.items[ key ];
2389 } else if ( mw.loader.store.items[ key ].length > mw.loader.store.MODULE_SIZE_MAX ) {
2390 // This value predates the enforcement of a size limit on cached modules.
2391 delete mw.loader.store.items[ key ];
2392 }
2393 }
2394 return true;
2395 },
2396
2397 /**
2398 * Clear the entire module store right now.
2399 */
2400 clear: function () {
2401 mw.loader.store.items = {};
2402 try {
2403 localStorage.removeItem( mw.loader.store.getStoreKey() );
2404 } catch ( ignored ) {}
2405 },
2406
2407 /**
2408 * Sync in-memory store back to localStorage.
2409 *
2410 * This function debounces updates. When called with a flush already pending,
2411 * the call is coalesced into the pending update. The call to
2412 * localStorage.setItem will be naturally deferred until the page is quiescent.
2413 *
2414 * Because localStorage is shared by all pages from the same origin, if multiple
2415 * pages are loaded with different module sets, the possibility exists that
2416 * modules saved by one page will be clobbered by another. But the impact would
2417 * be minor and the problem would be corrected by subsequent page views.
2418 *
2419 * @method
2420 */
2421 update: ( function () {
2422 var hasPendingWrite = false;
2423
2424 function flushWrites() {
2425 var data, key;
2426 if ( !hasPendingWrite || !mw.loader.store.enabled ) {
2427 return;
2428 }
2429
2430 mw.loader.store.prune();
2431 key = mw.loader.store.getStoreKey();
2432 try {
2433 // Replacing the content of the module store might fail if the new
2434 // contents would exceed the browser's localStorage size limit. To
2435 // avoid clogging the browser with stale data, always remove the old
2436 // value before attempting to set the new one.
2437 localStorage.removeItem( key );
2438 data = JSON.stringify( mw.loader.store );
2439 localStorage.setItem( key, data );
2440 } catch ( e ) {
2441 mw.track( 'resourceloader.exception', { exception: e, source: 'store-localstorage-update' } );
2442 }
2443
2444 hasPendingWrite = false;
2445 }
2446
2447 return function () {
2448 if ( !hasPendingWrite ) {
2449 hasPendingWrite = true;
2450 mw.requestIdleCallback( flushWrites );
2451 }
2452 };
2453 }() )
2454 }
2455 };
2456 }() ),
2457
2458 /**
2459 * HTML construction helper functions
2460 *
2461 * @example
2462 *
2463 * var Html, output;
2464 *
2465 * Html = mw.html;
2466 * output = Html.element( 'div', {}, new Html.Raw(
2467 * Html.element( 'img', { src: '<' } )
2468 * ) );
2469 * mw.log( output ); // <div><img src="&lt;"/></div>
2470 *
2471 * @class mw.html
2472 * @singleton
2473 */
2474 html: ( function () {
2475 function escapeCallback( s ) {
2476 switch ( s ) {
2477 case '\'':
2478 return '&#039;';
2479 case '"':
2480 return '&quot;';
2481 case '<':
2482 return '&lt;';
2483 case '>':
2484 return '&gt;';
2485 case '&':
2486 return '&amp;';
2487 }
2488 }
2489
2490 return {
2491 /**
2492 * Escape a string for HTML.
2493 *
2494 * Converts special characters to HTML entities.
2495 *
2496 * mw.html.escape( '< > \' & "' );
2497 * // Returns &lt; &gt; &#039; &amp; &quot;
2498 *
2499 * @param {string} s The string to escape
2500 * @return {string} HTML
2501 */
2502 escape: function ( s ) {
2503 return s.replace( /['"<>&]/g, escapeCallback );
2504 },
2505
2506 /**
2507 * Create an HTML element string, with safe escaping.
2508 *
2509 * @param {string} name The tag name.
2510 * @param {Object} [attrs] An object with members mapping element names to values
2511 * @param {string|mw.html.Raw|mw.html.Cdata|null} [contents=null] The contents of the element.
2512 *
2513 * - string: Text to be escaped.
2514 * - null: The element is treated as void with short closing form, e.g. `<br/>`.
2515 * - this.Raw: The raw value is directly included.
2516 * - this.Cdata: The raw value is directly included. An exception is
2517 * thrown if it contains any illegal ETAGO delimiter.
2518 * See <https://www.w3.org/TR/html401/appendix/notes.html#h-B.3.2>.
2519 * @return {string} HTML
2520 */
2521 element: function ( name, attrs, contents ) {
2522 var v, attrName, s = '<' + name;
2523
2524 if ( attrs ) {
2525 for ( attrName in attrs ) {
2526 v = attrs[ attrName ];
2527 // Convert name=true, to name=name
2528 if ( v === true ) {
2529 v = attrName;
2530 // Skip name=false
2531 } else if ( v === false ) {
2532 continue;
2533 }
2534 s += ' ' + attrName + '="' + this.escape( String( v ) ) + '"';
2535 }
2536 }
2537 if ( contents === undefined || contents === null ) {
2538 // Self close tag
2539 s += '/>';
2540 return s;
2541 }
2542 // Regular open tag
2543 s += '>';
2544 switch ( typeof contents ) {
2545 case 'string':
2546 // Escaped
2547 s += this.escape( contents );
2548 break;
2549 case 'number':
2550 case 'boolean':
2551 // Convert to string
2552 s += String( contents );
2553 break;
2554 default:
2555 if ( contents instanceof this.Raw ) {
2556 // Raw HTML inclusion
2557 s += contents.value;
2558 } else if ( contents instanceof this.Cdata ) {
2559 // CDATA
2560 if ( /<\/[a-zA-z]/.test( contents.value ) ) {
2561 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
2562 }
2563 s += contents.value;
2564 } else {
2565 throw new Error( 'mw.html.element: Invalid type of contents' );
2566 }
2567 }
2568 s += '</' + name + '>';
2569 return s;
2570 },
2571
2572 /**
2573 * Wrapper object for raw HTML passed to mw.html.element().
2574 *
2575 * @class mw.html.Raw
2576 * @constructor
2577 * @param {string} value
2578 */
2579 Raw: function ( value ) {
2580 this.value = value;
2581 },
2582
2583 /**
2584 * Wrapper object for CDATA element contents passed to mw.html.element()
2585 *
2586 * @class mw.html.Cdata
2587 * @constructor
2588 * @param {string} value
2589 */
2590 Cdata: function ( value ) {
2591 this.value = value;
2592 }
2593 };
2594 }() ),
2595
2596 // Skeleton user object, extended by the 'mediawiki.user' module.
2597 /**
2598 * @class mw.user
2599 * @singleton
2600 */
2601 user: {
2602 /**
2603 * @property {mw.Map}
2604 */
2605 options: new Map(),
2606 /**
2607 * @property {mw.Map}
2608 */
2609 tokens: new Map()
2610 },
2611
2612 // OOUI widgets specific to MediaWiki
2613 widgets: {},
2614
2615 /**
2616 * Registry and firing of events.
2617 *
2618 * MediaWiki has various interface components that are extended, enhanced
2619 * or manipulated in some other way by extensions, gadgets and even
2620 * in core itself.
2621 *
2622 * This framework helps streamlining the timing of when these other
2623 * code paths fire their plugins (instead of using document-ready,
2624 * which can and should be limited to firing only once).
2625 *
2626 * Features like navigating to other wiki pages, previewing an edit
2627 * and editing itself – without a refresh – can then retrigger these
2628 * hooks accordingly to ensure everything still works as expected.
2629 *
2630 * Example usage:
2631 *
2632 * mw.hook( 'wikipage.content' ).add( fn ).remove( fn );
2633 * mw.hook( 'wikipage.content' ).fire( $content );
2634 *
2635 * Handlers can be added and fired for arbitrary event names at any time. The same
2636 * event can be fired multiple times. The last run of an event is memorized
2637 * (similar to `$(document).ready` and `$.Deferred().done`).
2638 * This means if an event is fired, and a handler added afterwards, the added
2639 * function will be fired right away with the last given event data.
2640 *
2641 * Like Deferreds and Promises, the mw.hook object is both detachable and chainable.
2642 * Thus allowing flexible use and optimal maintainability and authority control.
2643 * You can pass around the `add` and/or `fire` method to another piece of code
2644 * without it having to know the event name (or `mw.hook` for that matter).
2645 *
2646 * var h = mw.hook( 'bar.ready' );
2647 * new mw.Foo( .. ).fetch( { callback: h.fire } );
2648 *
2649 * Note: Events are documented with an underscore instead of a dot in the event
2650 * name due to jsduck not supporting dots in that position.
2651 *
2652 * @class mw.hook
2653 */
2654 hook: ( function () {
2655 var lists = {};
2656
2657 /**
2658 * Create an instance of mw.hook.
2659 *
2660 * @method hook
2661 * @member mw
2662 * @param {string} name Name of hook.
2663 * @return {mw.hook}
2664 */
2665 return function ( name ) {
2666 var list = hasOwn.call( lists, name ) ?
2667 lists[ name ] :
2668 lists[ name ] = $.Callbacks( 'memory' );
2669
2670 return {
2671 /**
2672 * Register a hook handler
2673 *
2674 * @param {...Function} handler Function to bind.
2675 * @chainable
2676 */
2677 add: list.add,
2678
2679 /**
2680 * Unregister a hook handler
2681 *
2682 * @param {...Function} handler Function to unbind.
2683 * @chainable
2684 */
2685 remove: list.remove,
2686
2687 // eslint-disable-next-line valid-jsdoc
2688 /**
2689 * Run a hook.
2690 *
2691 * @param {...Mixed} data
2692 * @chainable
2693 */
2694 fire: function () {
2695 return list.fireWith.call( this, null, slice.call( arguments ) );
2696 }
2697 };
2698 };
2699 }() )
2700 };
2701
2702 // Alias $j to jQuery for backwards compatibility
2703 // @deprecated since 1.23 Use $ or jQuery instead
2704 mw.log.deprecate( window, '$j', $, 'Use $ or jQuery instead.' );
2705
2706 /**
2707 * Log a message to window.console, if possible.
2708 *
2709 * Useful to force logging of some errors that are otherwise hard to detect (i.e., this logs
2710 * also in production mode). Gets console references in each invocation instead of caching the
2711 * reference, so that debugging tools loaded later are supported (e.g. Firebug Lite in IE).
2712 *
2713 * @private
2714 * @param {string} topic Stream name passed by mw.track
2715 * @param {Object} data Data passed by mw.track
2716 * @param {Error} [data.exception]
2717 * @param {string} data.source Error source
2718 * @param {string} [data.module] Name of module which caused the error
2719 */
2720 function logError( topic, data ) {
2721 /* eslint-disable no-console */
2722 var msg,
2723 e = data.exception,
2724 source = data.source,
2725 module = data.module,
2726 console = window.console;
2727
2728 if ( console && console.log ) {
2729 msg = ( e ? 'Exception' : 'Error' ) + ' in ' + source;
2730 if ( module ) {
2731 msg += ' in module ' + module;
2732 }
2733 msg += ( e ? ':' : '.' );
2734 console.log( msg );
2735
2736 // If we have an exception object, log it to the error channel to trigger
2737 // proper stacktraces in browsers that support it. No fallback as we have
2738 // no browsers that don't support error(), but do support log().
2739 if ( e && console.error ) {
2740 console.error( String( e ), e );
2741 }
2742 }
2743 /* eslint-enable no-console */
2744 }
2745
2746 // Subscribe to error streams
2747 mw.trackSubscribe( 'resourceloader.exception', logError );
2748 mw.trackSubscribe( 'resourceloader.assert', logError );
2749
2750 /**
2751 * Fired when all modules associated with the page have finished loading.
2752 *
2753 * @event resourceloader_loadEnd
2754 * @member mw.hook
2755 */
2756 $( function () {
2757 var loading = $.grep( mw.loader.getModuleNames(), function ( module ) {
2758 return mw.loader.getState( module ) === 'loading';
2759 } );
2760 // We only need a callback, not any actual module. First try a single using()
2761 // for all loading modules. If one fails, fall back to tracking each module
2762 // separately via $.when(), this is expensive.
2763 loading = mw.loader.using( loading ).then( null, function () {
2764 var all = loading.map( function ( module ) {
2765 return mw.loader.using( module ).then( null, function () {
2766 return $.Deferred().resolve();
2767 } );
2768 } );
2769 return $.when.apply( $, all );
2770 } );
2771 loading.then( function () {
2772 /* global mwPerformance */
2773 mwPerformance.mark( 'mwLoadEnd' );
2774 mw.hook( 'resourceloader.loadEnd' ).fire();
2775 } );
2776 } );
2777
2778 // Attach to window and globally alias
2779 window.mw = window.mediaWiki = mw;
2780 }( jQuery ) );