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