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