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