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