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