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