Debian Codegraph @

closure-library/closure/goog/module/moduleloader.js

raw
1 // Copyright 2008 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview The module loader for loading modules across the network.
17 *
18 * Browsers do not guarantee that scripts appended to the document
19 * are executed in the order they are added. For production mode, we use
20 * XHRs to load scripts, because they do not have this problem and they
21 * have superior mechanisms for handling failure. However, XHR-evaled
22 * scripts are harder to debug.
23 *
24 * In debugging mode, we use normal script tags. In order to make this work,
25 * we load the scripts in serial: we do not execute script B to the document
26 * until we are certain that script A is finished loading.
27 *
28 */
29
30 goog.provide('goog.module.ModuleLoader');
31
32 goog.require('goog.Timer');
33 goog.require('goog.array');
34 goog.require('goog.events');
35 goog.require('goog.events.Event');
36 goog.require('goog.events.EventHandler');
37 goog.require('goog.events.EventId');
38 goog.require('goog.events.EventTarget');
39 goog.require('goog.html.TrustedResourceUrl');
40 goog.require('goog.labs.userAgent.browser');
41 goog.require('goog.log');
42 goog.require('goog.module.AbstractModuleLoader');
43 goog.require('goog.net.BulkLoader');
44 goog.require('goog.net.EventType');
45 goog.require('goog.net.jsloader');
46 goog.require('goog.userAgent');
47 goog.require('goog.userAgent.product');
48
49
50
51 /**
52 * A class that loads Javascript modules.
53 * @constructor
54 * @extends {goog.events.EventTarget}
55 * @implements {goog.module.AbstractModuleLoader}
56 */
57 goog.module.ModuleLoader = function() {
58 goog.module.ModuleLoader.base(this, 'constructor');
59
60 /**
61 * Event handler for managing handling events.
62 * @type {goog.events.EventHandler<!goog.module.ModuleLoader>}
63 * @private
64 */
65 this.eventHandler_ = new goog.events.EventHandler(this);
66
67 /**
68 * A map from module IDs to goog.module.ModuleLoader.LoadStatus.
69 * @type {!Object<Array<string>, goog.module.ModuleLoader.LoadStatus>}
70 * @private
71 */
72 this.loadingModulesStatus_ = {};
73 };
74 goog.inherits(goog.module.ModuleLoader, goog.events.EventTarget);
75
76
77 /**
78 * A logger.
79 * @type {goog.log.Logger}
80 * @protected
81 */
82 goog.module.ModuleLoader.prototype.logger =
83 goog.log.getLogger('goog.module.ModuleLoader');
84
85
86 /**
87 * Whether debug mode is enabled.
88 * @type {boolean}
89 * @private
90 */
91 goog.module.ModuleLoader.prototype.debugMode_ = false;
92
93
94 /**
95 * Whether source url injection is enabled.
96 * @type {boolean}
97 * @private
98 */
99 goog.module.ModuleLoader.prototype.sourceUrlInjection_ = false;
100
101
102 /**
103 * @return {boolean} Whether sourceURL affects stack traces.
104 */
105 goog.module.ModuleLoader.supportsSourceUrlStackTraces = function() {
106 return goog.userAgent.product.CHROME ||
107 (goog.labs.userAgent.browser.isFirefox() &&
108 goog.labs.userAgent.browser.isVersionOrHigher('36'));
109 };
110
111
112 /**
113 * @return {boolean} Whether sourceURL affects the debugger.
114 */
115 goog.module.ModuleLoader.supportsSourceUrlDebugger = function() {
116 return goog.userAgent.product.CHROME || goog.userAgent.GECKO;
117 };
118
119
120 /**
121 * Gets the debug mode for the loader.
122 * @return {boolean} Whether the debug mode is enabled.
123 */
124 goog.module.ModuleLoader.prototype.getDebugMode = function() {
125 return this.debugMode_;
126 };
127
128
129 /**
130 * Sets the debug mode for the loader.
131 * @param {boolean} debugMode Whether the debug mode is enabled.
132 */
133 goog.module.ModuleLoader.prototype.setDebugMode = function(debugMode) {
134 this.debugMode_ = debugMode;
135 };
136
137
138 /**
139 * When enabled, we will add a sourceURL comment to the end of all scripts
140 * to mark their origin.
141 *
142 * On WebKit, stack traces will reflect the sourceURL comment, so this is
143 * useful for debugging webkit stack traces in production.
144 *
145 * Notice that in debug mode, we will use source url injection + eval rather
146 * then appending script nodes to the DOM, because the scripts will load far
147 * faster. (Appending script nodes is very slow, because we can't parallelize
148 * the downloading and evaling of the script).
149 *
150 * The cost of appending sourceURL information is negligible when compared to
151 * the cost of evaling the script. Almost all clients will want this on.
152 *
153 * TODO(nicksantos): Turn this on by default. We may want to turn this off
154 * for clients that inject their own sourceURL.
155 *
156 * @param {boolean} enabled Whether source url injection is enabled.
157 */
158 goog.module.ModuleLoader.prototype.setSourceUrlInjection = function(enabled) {
159 this.sourceUrlInjection_ = enabled;
160 };
161
162
163 /**
164 * @return {boolean} Whether we're using source url injection.
165 * @private
166 */
167 goog.module.ModuleLoader.prototype.usingSourceUrlInjection_ = function() {
168 return this.sourceUrlInjection_ ||
169 (this.getDebugMode() &&
170 goog.module.ModuleLoader.supportsSourceUrlStackTraces());
171 };
172
173
174 /** @override */
175 goog.module.ModuleLoader.prototype.loadModules = function(
176 ids, moduleInfoMap, opt_successFn, opt_errorFn, opt_timeoutFn,
177 opt_forceReload) {
178 var loadStatus = this.loadingModulesStatus_[ids] ||
179 new goog.module.ModuleLoader.LoadStatus();
180 loadStatus.loadRequested = true;
181 loadStatus.successFn = opt_successFn || null;
182 loadStatus.errorFn = opt_errorFn || null;
183
184 if (!this.loadingModulesStatus_[ids]) {
185 // Modules were not prefetched.
186 this.loadingModulesStatus_[ids] = loadStatus;
187 this.downloadModules_(ids, moduleInfoMap);
188 // TODO(user): Need to handle timeouts in the module loading code.
189 } else if (goog.isDefAndNotNull(loadStatus.responseTexts)) {
190 // Modules prefetch is complete.
191 this.evaluateCode_(ids);
192 }
193 // Otherwise modules prefetch is in progress, and these modules will be
194 // executed after the prefetch is complete.
195 };
196
197
198 /**
199 * Evaluate the JS code.
200 * @param {Array<string>} moduleIds The module ids.
201 * @private
202 */
203 goog.module.ModuleLoader.prototype.evaluateCode_ = function(moduleIds) {
204 this.dispatchEvent(
205 new goog.module.ModuleLoader.RequestSuccessEvent(moduleIds));
206
207 goog.log.info(this.logger, 'evaluateCode ids:' + moduleIds);
208 var loadStatus = this.loadingModulesStatus_[moduleIds];
209 var uris = loadStatus.requestUris;
210 var texts = loadStatus.responseTexts;
211 var error = null;
212 try {
213 if (this.usingSourceUrlInjection_()) {
214 for (var i = 0; i < uris.length; i++) {
215 var uri = uris[i];
216 goog.globalEval(texts[i] + ' //# sourceURL=' + uri);
217 }
218 } else {
219 goog.globalEval(texts.join('\n'));
220 }
221 } catch (e) {
222 error = e;
223 // TODO(user): Consider throwing an exception here.
224 goog.log.warning(
225 this.logger, 'Loaded incomplete code for module(s): ' + moduleIds, e);
226 }
227
228 this.dispatchEvent(new goog.module.ModuleLoader.EvaluateCodeEvent(moduleIds));
229
230 if (error) {
231 this.handleErrorHelper_(
232 moduleIds, loadStatus.errorFn, null /* status */, error);
233 } else if (loadStatus.successFn) {
234 loadStatus.successFn();
235 }
236 delete this.loadingModulesStatus_[moduleIds];
237 };
238
239
240 /**
241 * Handles a successful response to a request for prefetch or load one or more
242 * modules.
243 *
244 * @param {goog.net.BulkLoader} bulkLoader The bulk loader.
245 * @param {Array<string>} moduleIds The ids of the modules requested.
246 * @private
247 */
248 goog.module.ModuleLoader.prototype.handleSuccess_ = function(
249 bulkLoader, moduleIds) {
250 goog.log.info(this.logger, 'Code loaded for module(s): ' + moduleIds);
251
252 var loadStatus = this.loadingModulesStatus_[moduleIds];
253 loadStatus.responseTexts = bulkLoader.getResponseTexts();
254
255 if (loadStatus.loadRequested) {
256 this.evaluateCode_(moduleIds);
257 }
258
259 // NOTE: A bulk loader instance is used for loading a set of module ids.
260 // Once these modules have been loaded successfully or in error the bulk
261 // loader should be disposed as it is not needed anymore. A new bulk loader
262 // is instantiated for any new modules to be loaded. The dispose is called
263 // on a timer so that the bulkloader has a chance to release its
264 // objects.
265 goog.Timer.callOnce(bulkLoader.dispose, 5, bulkLoader);
266 };
267
268
269 /** @override */
270 goog.module.ModuleLoader.prototype.prefetchModule = function(id, moduleInfo) {
271 // Do not prefetch in debug mode.
272 if (this.getDebugMode()) {
273 return;
274 }
275 var loadStatus = this.loadingModulesStatus_[[id]];
276 if (loadStatus) {
277 return;
278 }
279
280 var moduleInfoMap = {};
281 moduleInfoMap[id] = moduleInfo;
282 this.loadingModulesStatus_[[id]] = new goog.module.ModuleLoader.LoadStatus();
283 this.downloadModules_([id], moduleInfoMap);
284 };
285
286
287 /**
288 * Downloads a list of JavaScript modules.
289 *
290 * @param {Array<string>} ids The module ids in dependency order.
291 * @param {!Object<string, !goog.module.ModuleInfo>} moduleInfoMap A mapping
292 * from module id to ModuleInfo object.
293 * @private
294 */
295 goog.module.ModuleLoader.prototype.downloadModules_ = function(
296 ids, moduleInfoMap) {
297 var trustedUris = [];
298 for (var i = 0; i < ids.length; i++) {
299 goog.array.extend(trustedUris, moduleInfoMap[ids[i]].getUris());
300 }
301 var uris = goog.array.map(trustedUris, goog.html.TrustedResourceUrl.unwrap);
302 goog.log.info(this.logger, 'downloadModules ids:' + ids + ' uris:' + uris);
303
304 if (this.getDebugMode() && !this.usingSourceUrlInjection_()) {
305 // In debug mode use <script> tags rather than XHRs to load the files.
306 // This makes it possible to debug and inspect stack traces more easily.
307 // It's also possible to use it to load JavaScript files that are hosted on
308 // another domain.
309 // The scripts need to load serially, so this is much slower than parallel
310 // script loads with source url injection.
311 goog.net.jsloader.safeLoadMany(trustedUris);
312 } else {
313 var loadStatus = this.loadingModulesStatus_[ids];
314 loadStatus.requestUris = uris;
315
316 var bulkLoader = new goog.net.BulkLoader(uris);
317
318 var eventHandler = this.eventHandler_;
319 eventHandler.listen(
320 bulkLoader, goog.net.EventType.SUCCESS,
321 goog.bind(this.handleSuccess_, this, bulkLoader, ids));
322 eventHandler.listen(
323 bulkLoader, goog.net.EventType.ERROR,
324 goog.bind(this.handleError_, this, bulkLoader, ids));
325 bulkLoader.load();
326 }
327 };
328
329
330 /**
331 * Handles an error during a request for one or more modules.
332 * @param {goog.net.BulkLoader} bulkLoader The bulk loader.
333 * @param {Array<string>} moduleIds The ids of the modules requested.
334 * @param {number} status The response status.
335 * @private
336 */
337 goog.module.ModuleLoader.prototype.handleError_ = function(
338 bulkLoader, moduleIds, status) {
339 var loadStatus = this.loadingModulesStatus_[moduleIds];
340 // The bulk loader doesn't cancel other requests when a request fails. We will
341 // delete the loadStatus in the first failure, so it will be undefined in
342 // subsequent errors.
343 if (loadStatus) {
344 delete this.loadingModulesStatus_[moduleIds];
345 this.handleErrorHelper_(moduleIds, loadStatus.errorFn, status);
346 }
347
348 // NOTE: A bulk loader instance is used for loading a set of module ids. Once
349 // these modules have been loaded successfully or in error the bulk loader
350 // should be disposed as it is not needed anymore. A new bulk loader is
351 // instantiated for any new modules to be loaded. The dispose is called
352 // on another thread so that the bulkloader has a chance to release its
353 // objects.
354 goog.Timer.callOnce(bulkLoader.dispose, 5, bulkLoader);
355 };
356
357
358 /**
359 * Handles an error during a request for one or more modules.
360 * @param {Array<string>} moduleIds The ids of the modules requested.
361 * @param {?function(?number)} errorFn The function to call on failure.
362 * @param {?number} status The response status.
363 * @param {!Error=} opt_error The error encountered, if available.
364 * @private
365 */
366 goog.module.ModuleLoader.prototype.handleErrorHelper_ = function(
367 moduleIds, errorFn, status, opt_error) {
368 this.dispatchEvent(
369 new goog.module.ModuleLoader.RequestErrorEvent(moduleIds, opt_error));
370
371 goog.log.warning(this.logger, 'Request failed for module(s): ' + moduleIds);
372
373 if (errorFn) {
374 errorFn(status);
375 }
376 };
377
378
379 /** @override */
380 goog.module.ModuleLoader.prototype.disposeInternal = function() {
381 goog.module.ModuleLoader.superClass_.disposeInternal.call(this);
382
383 this.eventHandler_.dispose();
384 this.eventHandler_ = null;
385 };
386
387
388 /**
389 * Events dispatched by the ModuleLoader.
390 * @const
391 */
392 goog.module.ModuleLoader.EventType = {
393 /**
394 * @const {!goog.events.EventId<
395 * !goog.module.ModuleLoader.EvaluateCodeEvent>} Called after the code for
396 * a module is evaluated.
397 */
398 EVALUATE_CODE:
399 new goog.events.EventId(goog.events.getUniqueId('evaluateCode')),
400
401 /**
402 * @const {!goog.events.EventId<
403 * !goog.module.ModuleLoader.RequestSuccessEvent>} Called when the
404 * BulkLoader finishes successfully.
405 */
406 REQUEST_SUCCESS:
407 new goog.events.EventId(goog.events.getUniqueId('requestSuccess')),
408
409 /**
410 * @const {!goog.events.EventId<
411 * !goog.module.ModuleLoader.RequestErrorEvent>} Called when the
412 * BulkLoader fails, or code loading fails.
413 */
414 REQUEST_ERROR:
415 new goog.events.EventId(goog.events.getUniqueId('requestError'))
416 };
417
418
419
420 /**
421 * @param {Array<string>} moduleIds The ids of the modules being evaluated.
422 * @constructor
423 * @extends {goog.events.Event}
424 * @final
425 * @protected
426 */
427 goog.module.ModuleLoader.EvaluateCodeEvent = function(moduleIds) {
428 goog.module.ModuleLoader.EvaluateCodeEvent.base(
429 this, 'constructor', goog.module.ModuleLoader.EventType.EVALUATE_CODE);
430
431 /**
432 * @type {Array<string>}
433 */
434 this.moduleIds = moduleIds;
435 };
436 goog.inherits(goog.module.ModuleLoader.EvaluateCodeEvent, goog.events.Event);
437
438
439
440 /**
441 * @param {Array<string>} moduleIds The ids of the modules being evaluated.
442 * @constructor
443 * @extends {goog.events.Event}
444 * @final
445 * @protected
446 */
447 goog.module.ModuleLoader.RequestSuccessEvent = function(moduleIds) {
448 goog.module.ModuleLoader.RequestSuccessEvent.base(
449 this, 'constructor', goog.module.ModuleLoader.EventType.REQUEST_SUCCESS);
450
451 /**
452 * @type {Array<string>}
453 */
454 this.moduleIds = moduleIds;
455 };
456 goog.inherits(goog.module.ModuleLoader.RequestSuccessEvent, goog.events.Event);
457
458
459
460 /**
461 * @param {Array<string>} moduleIds The ids of the modules being evaluated.
462 * @param {!Error=} opt_error The error encountered, if available.
463 * @constructor
464 * @extends {goog.events.Event}
465 * @final
466 * @protected
467 */
468 goog.module.ModuleLoader.RequestErrorEvent = function(moduleIds, opt_error) {
469 goog.module.ModuleLoader.RequestErrorEvent.base(
470 this, 'constructor', goog.module.ModuleLoader.EventType.REQUEST_ERROR);
471
472 /**
473 * @type {Array<string>}
474 */
475 this.moduleIds = moduleIds;
476
477 /** @type {?Error} */
478 this.error = opt_error || null;
479 };
480 goog.inherits(goog.module.ModuleLoader.RequestErrorEvent, goog.events.Event);
481
482
483
484 /**
485 * A class that keeps the state of the module during the loading process. It is
486 * used to save loading information between modules download and evaluation.
487 * @constructor
488 * @final
489 */
490 goog.module.ModuleLoader.LoadStatus = function() {
491 /**
492 * The request uris.
493 * @type {Array<string>}
494 */
495 this.requestUris = null;
496
497 /**
498 * The response texts.
499 * @type {Array<string>}
500 */
501 this.responseTexts = null;
502
503 /**
504 * Whether loadModules was called for the set of modules referred by this
505 * status.
506 * @type {boolean}
507 */
508 this.loadRequested = false;
509
510 /**
511 * Success callback.
512 * @type {?function()}
513 */
514 this.successFn = null;
515
516 /**
517 * Error callback.
518 * @type {?function(?number)}
519 */
520 this.errorFn = null;
521 };