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