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