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