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