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