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