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