forked from montagejs/mr
-
Notifications
You must be signed in to change notification settings - Fork 1
/
boot.js
4494 lines (3966 loc) · 146 KB
/
boot.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
global = this;
(function (modules) {
// Bundle allows the run-time to extract already-loaded modules from the
// boot bundle.
var bundle = {};
// Unpack module tuples into module objects.
for (var i = 0; i < modules.length; i++) {
var module = modules[i];
modules[i] = new Module(module[0], module[1], module[2], module[3]);
bundle[module[0]] = bundle[module[1]] || {};
bundle[module[0]][module[1]] = module;
}
function Module(name, id, map, factory) {
// Package name and module identifier are purely informative.
this.name = name;
this.id = id;
// Dependency map and factory are used to instantiate bundled modules.
this.map = map;
this.factory = factory;
}
Module.prototype.getExports = function () {
var module = this;
if (module.exports === void 0) {
module.exports = {};
var require = function (id) {
var index = module.map[id];
var dependency = modules[index];
if (!dependency)
throw new Error("Bundle is missing a dependency: " + id);
return dependency.getExports();
}
module.exports = module.factory(require, module.exports, module) || module.exports;
}
return module.exports;
};
// Communicate the bundle to all bundled modules
Module.prototype.bundle = bundle;
return modules[0].getExports();
})((function (global){return[["mr","boot/require",{"../require":4,"url":8,"q":15,"./script-params":3},function (require, exports, module){
// mr boot/require
// ---------------
"use strict";
var Require = require("../require");
var URL = require("url");
var Q = require("q");
var getParams = require("./script-params");
module.exports = boot;
function boot(preloaded, params) {
params = params || getParams("boot.js");
var config = {preloaded: preloaded};
var applicationLocation = URL.resolve(window.location, params.package || ".");
var moduleId = params.module || "";
if ("autoPackage" in params) {
Require.injectPackageDescription(applicationLocation, {});
}
return Require.loadPackage({
location: applicationLocation,
hash: params.applicationHash
}, {
bundle: module.bundle
})
.then(function (applicationRequire) {
return applicationRequire.loadPackage({
name: "mr",
location: params.mrLocation,
hash: params.mrHash
})
.then(function (mrRequire) {
return mrRequire.loadPackage({
name: "q",
location: params.qLocation,
hash: params.qHash
})
.then(function (qRequire) {
qRequire.inject("q", Q);
mrRequire.inject("mini-url", URL);
mrRequire.inject("require", Require);
return applicationRequire.async(moduleId);
});
});
});
}
}],["asap","browser-asap",{"./raw":2},function (require, exports, module){
// asap browser-asap
// -----------------
"use strict";
// rawAsap provides everything we need except exception management.
var rawAsap = require("./raw");
// RawTasks are recycled to reduce GC churn.
var freeTasks = [];
// We queue errors to ensure they are thrown in right order (FIFO).
// Array-as-queue is good enough here, since we are just dealing with exceptions.
var pendingErrors = [];
var requestErrorThrow = rawAsap.makeRequestCallFromTimer(throwFirstError);
function throwFirstError() {
if (pendingErrors.length) {
throw pendingErrors.shift();
}
}
/**
* Calls a task as soon as possible after returning, in its own event, with priority
* over other events like animation, reflow, and repaint. An error thrown from an
* event will not interrupt, nor even substantially slow down the processing of
* other events, but will be rather postponed to a lower priority event.
* @param {{call}} task A callable object, typically a function that takes no
* arguments.
*/
module.exports = asap;
function asap(task) {
var rawTask;
if (freeTasks.length) {
rawTask = freeTasks.pop();
} else {
rawTask = new RawTask();
}
rawTask.task = task;
rawAsap(rawTask);
}
// We wrap tasks with recyclable task objects. A task object implements
// `call`, just like a function.
function RawTask() {
this.task = null;
}
// The sole purpose of wrapping the task is to catch the exception and recycle
// the task object after its single use.
RawTask.prototype.call = function () {
try {
this.task.call();
} catch (error) {
if (asap.onerror) {
// This hook exists purely for testing purposes.
// Its name will be periodically randomized to break any code that
// depends on its existence.
asap.onerror(error);
} else {
// In a web browser, exceptions are not fatal. However, to avoid
// slowing down the queue of pending tasks, we rethrow the error in a
// lower priority turn.
pendingErrors.push(error);
requestErrorThrow();
}
} finally {
this.task = null;
freeTasks[freeTasks.length] = this;
}
};
}],["asap","browser-raw",{},function (require, exports, module){
// asap browser-raw
// ----------------
"use strict";
// Use the fastest means possible to execute a task in its own turn, with
// priority over other events including IO, animation, reflow, and redraw
// events in browsers.
//
// An exception thrown by a task will permanently interrupt the processing of
// subsequent tasks. The higher level `asap` function ensures that if an
// exception is thrown by a task, that the task queue will continue flushing as
// soon as possible, but if you use `rawAsap` directly, you are responsible to
// either ensure that no exceptions are thrown from your task, or to manually
// call `rawAsap.requestFlush` if an exception is thrown.
module.exports = rawAsap;
function rawAsap(task) {
if (!queue.length) {
requestFlush();
flushing = true;
}
// Equivalent to push, but avoids a function call.
queue[queue.length] = task;
}
var queue = [];
// Once a flush has been requested, no further calls to `requestFlush` are
// necessary until the next `flush` completes.
var flushing = false;
// `requestFlush` is an implementation-specific method that attempts to kick
// off a `flush` event as quickly as possible. `flush` will attempt to exhaust
// the event queue before yielding to the browser's own event loop.
var requestFlush;
// The position of the next task to execute in the task queue. This is
// preserved between calls to `flush` so that it can be resumed if
// a task throws an exception.
var index = 0;
// If a task schedules additional tasks recursively, the task queue can grow
// unbounded. To prevent memory exhaustion, the task queue will periodically
// truncate already-completed tasks.
var capacity = 1024;
// The flush function processes all tasks that have been scheduled with
// `rawAsap` unless and until one of those tasks throws an exception.
// If a task throws an exception, `flush` ensures that its state will remain
// consistent and will resume where it left off when called again.
// However, `flush` does not make any arrangements to be called again if an
// exception is thrown.
function flush() {
while (index < queue.length) {
var currentIndex = index;
// Advance the index before calling the task. This ensures that we will
// begin flushing on the next task the task throws an error.
index = index + 1;
queue[currentIndex].call();
// Prevent leaking memory for long chains of recursive calls to `asap`.
// If we call `asap` within tasks scheduled by `asap`, the queue will
// grow, but to avoid an O(n) walk for every task we execute, we don't
// shift tasks off the queue after they have been executed.
// Instead, we periodically shift 1024 tasks off the queue.
if (index > capacity) {
// Manually shift all values starting at the index back to the
// beginning of the queue.
for (var scan = 0; scan < index; scan++) {
queue[scan] = queue[scan + index];
}
queue.length -= index;
index = 0;
}
}
queue.length = 0;
index = 0;
flushing = false;
}
// `requestFlush` is implemented using a strategy based on data collected from
// every available SauceLabs Selenium web driver worker at time of writing.
// https://docs.google.com/spreadsheets/d/1mG-5UYGup5qxGdEMWkhP6BWCz053NUb2E1QoUTU16uA/edit#gid=783724593
// Safari 6 and 6.1 for desktop, iPad, and iPhone are the only browsers that
// have WebKitMutationObserver but not un-prefixed MutationObserver.
// Must use `global` instead of `window` to work in both frames and web
// workers. `global` is a provision of Browserify, Mr, Mrs, or Mop.
var BrowserMutationObserver = global.MutationObserver || global.WebKitMutationObserver;
// MutationObservers are desirable because they have high priority and work
// reliably everywhere they are implemented.
// They are implemented in all modern browsers.
//
// - Android 4-4.3
// - Chrome 26-34
// - Firefox 14-29
// - Internet Explorer 11
// - iPad Safari 6-7.1
// - iPhone Safari 7-7.1
// - Safari 6-7
if (typeof BrowserMutationObserver === "function") {
requestFlush = makeRequestCallFromMutationObserver(flush);
// MessageChannels are desirable because they give direct access to the HTML
// task queue, are implemented in Internet Explorer 10, Safari 5.0-1, and Opera
// 11-12, and in web workers in many engines.
// Although message channels yield to any queued rendering and IO tasks, they
// would be better than imposing the 4ms delay of timers.
// However, they do not work reliably in Internet Explorer or Safari.
// Internet Explorer 10 is the only browser that has setImmediate but does
// not have MutationObservers.
// Although setImmediate yields to the browser's renderer, it would be
// preferrable to falling back to setTimeout since it does not have
// the minimum 4ms penalty.
// Unfortunately there appears to be a bug in Internet Explorer 10 Mobile (and
// Desktop to a lesser extent) that renders both setImmediate and
// MessageChannel useless for the purposes of ASAP.
// https://github.com/kriskowal/q/issues/396
// Timers are implemented universally.
// We fall back to timers in workers in most engines, and in foreground
// contexts in the following browsers.
// However, note that even this simple case requires nuances to operate in a
// broad spectrum of browsers.
//
// - Firefox 3-13
// - Internet Explorer 6-9
// - iPad Safari 4.3
// - Lynx 2.8.7
} else {
requestFlush = makeRequestCallFromTimer(flush);
}
// `requestFlush` requests that the high priority event queue be flushed as
// soon as possible.
// This is useful to prevent an error thrown in a task from stalling the event
// queue if the exception handled by Node.js’s
// `process.on("uncaughtException")` or by a domain.
rawAsap.requestFlush = requestFlush;
// To request a high priority event, we induce a mutation observer by toggling
// the text of a text node between "1" and "-1".
function makeRequestCallFromMutationObserver(callback) {
var toggle = 1;
var observer = new BrowserMutationObserver(callback);
var node = document.createTextNode("");
observer.observe(node, {characterData: true});
return function requestCall() {
toggle = -toggle;
node.data = toggle;
};
}
// The message channel technique was discovered by Malte Ubl and was the
// original foundation for this library.
// http://www.nonblocking.io/2011/06/windownexttick.html
// Safari 6.0.5 (at least) intermittently fails to create message ports on a
// page's first load. Thankfully, this version of Safari supports
// MutationObservers, so we don't need to fall back in that case.
// function makeRequestCallFromMessageChannel(callback) {
// var channel = new MessageChannel();
// channel.port1.onmessage = callback;
// return function requestCall() {
// channel.port2.postMessage(0);
// };
// }
// For reasons explained above, we are also unable to use `setImmediate`
// under any circumstances.
// Even if we were, there is another bug in Internet Explorer 10.
// It is not sufficient to assign `setImmediate` to `requestFlush` because
// `setImmediate` must be called *by name* and therefore must be wrapped in a
// closure.
// Never forget.
// function makeRequestCallFromSetImmediate(callback) {
// return function requestCall() {
// setImmediate(callback);
// };
// }
// Safari 6.0 has a problem where timers will get lost while the user is
// scrolling. This problem does not impact ASAP because Safari 6.0 supports
// mutation observers, so that implementation is used instead.
// However, if we ever elect to use timers in Safari, the prevalent work-around
// is to add a scroll event listener that calls for a flush.
// `setTimeout` does not call the passed callback if the delay is less than
// approximately 7 in web workers in Firefox 8 through 18, and sometimes not
// even then.
function makeRequestCallFromTimer(callback) {
return function requestCall() {
// We dispatch a timeout with a specified delay of 0 for engines that
// can reliably accommodate that request. This will usually be snapped
// to a 4 milisecond delay, but once we're flushing, there's no delay
// between events.
var timeoutHandle = setTimeout(handleTimer, 0);
// However, since this timer gets frequently dropped in Firefox
// workers, we enlist an interval handle that will try to fire
// an event 20 times per second until it succeeds.
var intervalHandle = setInterval(handleTimer, 50);
function handleTimer() {
// Whichever timer succeeds will cancel both timers and
// execute the callback.
clearTimeout(timeoutHandle);
clearInterval(intervalHandle);
callback();
}
};
}
// This is for `asap.js` only.
// Its name will be periodically randomized to break any code that depends on
// its existence.
rawAsap.makeRequestCallFromTimer = makeRequestCallFromTimer;
// ASAP was originally a nextTick shim included in Q. This was factored out
// into this ASAP package. It was later adapted to RSVP which made further
// amendments. These decisions, particularly to marginalize MessageChannel and
// to capture the MutationObserver implementation in a closure, were integrated
// back into ASAP proper.
// https://github.com/tildeio/rsvp.js/blob/cddf7232546a9cf858524b75cde6f9edf72620a7/lib/rsvp/asap.js
}],["mr","boot/script-params",{"url":8},function (require, exports, module){
// mr boot/script-params
// ---------------------
var URL = require("url");
module.exports = getParams;
function getParams(scriptName) {
var i, j,
match,
script,
location,
attr,
name,
re = new RegExp("^(.*)" + scriptName + "(?:[\\?\\.]|$)", "i");
var params = {};
// Find the <script> that loads us, so we can divine our parameters
// from its attributes.
var scripts = document.getElementsByTagName("script");
for (i = 0; i < scripts.length; i++) {
script = scripts[i];
// There are two distinct ways that a bootstrapping script might be
// identified. In development, we can rely on the script name. In
// production, the script name is produced by the optimizer and does
// not have a generic pattern. However, the optimizer will drop a
// `data-boot-location` property on the script instead. This will also
// serve to inform the boot script of the location of the loading
// package, albeit Montage or Mr.
if (scriptName && script.src && (match = script.src.match(re))) {
location = match[1];
}
if (script.hasAttribute("data-boot-location")) {
location = URL.resolve(window.location, script.getAttribute("data-boot-location"));
}
if (location) {
if (script.dataset) {
for (name in script.dataset) {
if (script.dataset.hasOwnProperty(name)) {
params[name] = script.dataset[name];
}
}
} else if (script.attributes) {
var dataRe = /^data-(.*)$/,
letterAfterDash = /-([a-z])/g,
/*jshint -W083 */
upperCaseChar = function (_, c) {
return c.toUpperCase();
};
/*jshint +W083 */
for (j = 0; j < script.attributes.length; j++) {
attr = script.attributes[j];
match = attr.name.match(/^data-(.*)$/);
if (match) {
params[match[1].replace(letterAfterDash, upperCaseChar)] = attr.value;
}
}
}
// Permits multiple boot <scripts>; by removing as they are
// discovered, next one finds itself.
script.parentNode.removeChild(script);
params.location = location;
break;
}
}
return params;
}
}],["mr","browser",{"./common":5,"url":8,"q":15,"./script":10},function (require, exports, module){
// mr browser
// ----------
/*
* Based in part on Motorola Mobility’s Montage
* Copyright (c) 2012, Motorola Mobility LLC. All Rights Reserved.
* 3-Clause BSD License
* https://github.com/motorola-mobility/montage/blob/master/LICENSE.md
*/
/*global montageDefine:true, -URL */
/*jshint -W015, evil:true, camelcase:false */
var Require = require("./common");
var URL = require("url");
var Q = require("q");
var GET = "GET";
var APPLICATION_JAVASCRIPT_MIMETYPE = "application/javascript";
var FILE_PROTOCOL = "file:";
module.exports = Require;
Require.getLocation = function() {
return URL.resolve(window.location, ".");
};
Require.overlays = ["window", "browser", "montage"];
// Determine if an XMLHttpRequest was successful
// Some versions of WebKit return 0 for successful file:// URLs
function xhrSuccess(req) {
return (req.status === 200 || (req.status === 0 && req.responseText));
}
// Due to crazy variabile availability of new and old XHR APIs across
// platforms, this implementation registers every known name for the event
// listeners. The promise library ascertains that the returned promise
// is resolved only by the first event.
// http://dl.dropbox.com/u/131998/yui/misc/get/browser-capabilities.html
Require.read = function (location) {
if (URL.resolve(window.location, location).indexOf(FILE_PROTOCOL) === 0) {
throw new Error("XHR does not function for file: protocol");
}
var request = new XMLHttpRequest();
var response = Q.defer();
function onload() {
if (xhrSuccess(request)) {
response.resolve(request.responseText);
} else {
onerror();
}
}
function onerror() {
response.reject(new Error("Can't XHR " + JSON.stringify(location)));
}
try {
request.open(GET, location, true);
if (request.overrideMimeType) {
request.overrideMimeType(APPLICATION_JAVASCRIPT_MIMETYPE);
}
request.onreadystatechange = function () {
if (request.readyState === 4) {
onload();
}
};
request.onload = request.load = onload;
request.onerror = request.error = onerror;
} catch (exception) {
response.reject(exception);
}
request.send();
return response.promise;
};
// By using a named "eval" most browsers will execute in the global scope.
// http://www.davidflanagan.com/2010/12/global-eval-in.html
// Unfortunately execScript doesn't always return the value of the evaluated expression (at least in Chrome)
var globalEval = /*this.execScript ||*/eval;
// For Firebug evaled code isn't debuggable otherwise
// http://code.google.com/p/fbug/issues/detail?id=2198
if (global.navigator && global.navigator.userAgent.indexOf("Firefox") >= 0) {
globalEval = new Function("_", "return eval(_)");
}
var __FILE__String = "__FILE__",
Underscore = "_",
globalEvalConstantA = "(function ",
globalEvalConstantB = "(require, exports, module, __filename, __dirname) {",
globalEvalConstantC = "//*/\n})\n//@ sourceURL=";
Require.Compiler = function (config) {
return function(module) {
if (module.factory || module.text === void 0 || module.type !== "js") {
return;
}
if (config.useScriptInjection) {
throw new Error("Can't use eval.");
}
// Here we use a couple tricks to make debugging better in various browsers:
// TODO: determine if these are all necessary / the best options
// 1. name the function with something inteligible since some debuggers display the first part of each eval (Firebug)
// 2. append the "//@ sourceURL=location" hack (Safari, Chrome, Firebug)
// * http://pmuellr.blogspot.com/2009/06/debugger-friendly.html
// * http://blog.getfirebug.com/2009/08/11/give-your-eval-a-name-with-sourceurl/
// TODO: investigate why this isn't working in Firebug.
// 3. set displayName property on the factory function (Safari, Chrome)
var displayName = (module.require.config.name + Underscore + module.id).replace(/[^\w\d]|^\d/g, Underscore);
try {
module.factory = globalEval(globalEvalConstantA+displayName+globalEvalConstantB+module.text+globalEvalConstantC+module.location);
if (!config.saveText) {
delete module.text; // save some space
}
} catch (exception) {
exception.message = exception.message + " in " + module.location;
throw exception;
}
// This should work and would be simpler, but Firebug does not show scripts executed via "new Function()" constructor.
// TODO: sniff browser?
// module.factory = new Function("require", "exports", "module", module.text + "\n//*/"+sourceURLComment);
module.factory.displayName = displayName;
};
};
Require.XhrLoader = function (config) {
return function (location, module) {
return config.read(location)
.then(function (text) {
module.text = text;
module.location = location;
});
};
};
var definitions = {};
var getDefinition = function (hash, id) {
definitions[hash] = definitions[hash] || {};
definitions[hash][id] = definitions[hash][id] || Q.defer();
return definitions[hash][id];
};
// global
montageDefine = function (hash, id, module) {
getDefinition(hash, id).resolve(module);
};
Require.loadScript = require("./script");
Require.ScriptLoader = function (config) {
var hash = config.packageDescription.hash;
return function (location, module) {
return Q.try(function () {
// short-cut by predefinition
if (definitions[hash] && definitions[hash][module.id]) {
return definitions[hash][module.id].promise;
}
if (/\.js$/.test(location)) {
location = location.replace(/\.js/, ".load.js");
} else {
location += ".load.js";
}
Require.loadScript(location);
var definition = getDefinition(hash, module.id).promise;
loadIfNotPreloaded(location, definition, config.preloaded);
return definition;
})
.then(function (definition) {
/*jshint -W089 */
delete definitions[hash][module.id];
for (var name in definition) {
module[name] = definition[name];
}
module.location = location;
module.directory = URL.resolve(location, ".");
/*jshint +W089 */
});
};
};
// old version
var loadPackageDescription = Require.loadPackageDescription;
Require.loadPackageDescription = function (dependency, config) {
if (dependency.hash) { // use script injection
var definition = getDefinition(dependency.hash, "package.json").promise;
var location = URL.resolve(dependency.location, "package.json.load.js");
loadIfNotPreloaded(location, definition, config.preloaded);
return definition.get("exports");
} else {
// fall back to normal means
return loadPackageDescription(dependency, config);
}
};
Require.makeLoader = function (config) {
var Loader;
if (config.useScriptInjection) {
Loader = Require.ScriptLoader;
} else {
Loader = Require.XhrLoader;
}
return Require.CommonLoader(config, Loader(config));
};
function loadIfNotPreloaded(location, definition, preloaded) {
// The package.json might come in a preloading bundle. If so, we do not
// want to issue a script injection. However, if by the time preloading
// has finished the package.json has not arrived, we will need to kick off
// a request for the requested script.
if (preloaded && preloaded.isPending()) {
preloaded
.then(function () {
if (definition.isPending()) {
Require.loadScript(location);
}
})
.done();
} else if (definition.isPending()) {
// otherwise preloading has already completed and we don't have the
// module, so load it
Require.loadScript(location);
}
}
}],["mr","common",{"q":15,"url":8,"./merge":7,"./identifier":6,"./parse-dependencies":9},function (require, exports, module){
// mr common
// ---------
/*
* Based in part on Motorola Mobility’s Montage
* Copyright (c) 2012, Motorola Mobility LLC. All Rights Reserved.
* 3-Clause BSD License
* https://github.com/motorola-mobility/montage/blob/master/LICENSE.md
*/
/*global -URL */
/*jshint node:true */
var Require = exports;
var Q = require("q");
var URL = require("url");
var merge = require("./merge");
var Identifier = require("./identifier");
if (!this) {
throw new Error("Require does not work in strict mode.");
}
var globalEval = eval; // reassigning causes eval to not use lexical scope.
// Non-CommonJS speced extensions should be marked with an "// EXTENSION"
// comment.
Require.makeRequire = function (config) {
var require;
// Configuration defaults:
config = config || {};
config.location = URL.resolve(config.location || Require.getLocation(), "./");
config.paths = config.paths || [config.location];
config.mappings = config.mappings || {}; // EXTENSION
config.exposedConfigs = config.exposedConfigs || Require.exposedConfigs;
config.makeLoader = config.makeLoader || Require.makeLoader;
config.load = config.load || config.makeLoader(config);
config.makeCompiler = config.makeCompiler || Require.makeCompiler;
config.compile = config.compile || config.makeCompiler(config);
config.parseDependencies = config.parseDependencies || Require.parseDependencies;
config.read = config.read || Require.read;
config.optimizers = config.optimizers || {};
config.compilers = config.compilers || {};
config.translators = config.translators || {};
config.redirectTable = config.redirectTable || [];
// Modules: { exports, id, location, directory, factory, dependencies,
// dependees, text, type }
var modules = config.modules = config.modules || {};
// produces an entry in the module state table, which gets built
// up through loading and execution, ultimately serving as the
// ``module`` free variable inside the corresponding module.
function getModuleDescriptor(id) {
var lookupId = id.toLowerCase();
if (!has.call(modules, lookupId)) {
var extension = Identifier.extension(id);
var type;
if (
extension && (
has.call(config.optimizers, extension) ||
has.call(config.translators, extension) ||
has.call(config.compilers, extension)
)
) {
type = extension;
} else {
type = "js";
}
var module = {
id: id,
extension: extension,
type: type,
display: (config.name || config.location) + "#" + id,
require: makeRequire(id)
};
modules[lookupId] = module;
}
return modules[lookupId];
}
// for preloading modules by their id and exports, useful to
// prevent wasteful multiple instantiation if a module was loaded
// in the bootstrapping process and can be trivially injected into
// the system.
function inject(id, exports) {
var module = getModuleDescriptor(id);
module.exports = exports;
module.location = URL.resolve(config.location, id);
module.directory = URL.resolve(module.location, "./");
module.injected = true;
module.type = void 0;
delete module.redirect;
delete module.mappingRedirect;
}
// Ensures a module definition is loaded, compiled, analyzed
var load = memoize(function (topId, viaId, loading) {
var module = getModuleDescriptor(topId);
return Q.try(function () {
// If not already loaded, already instantiated, or configured as a
// redirection to another module.
if (
module.factory === void 0 &&
module.exports === void 0 &&
module.redirect === void 0
) {
return config.load(topId, module);
}
})
.then(function () {
// Translate (to JavaScript, optionally provide dependency analysis
// services).
if (module.type !== "js" && has.call(config.translators, module.type)) {
var translatorId = config.translators[module.type];
return Q.try(function () {
// The use of a preprocessor package is optional for
// translators, though mandatory for optimizers because
// there are .js to .js optimizers, but no such
// translators.
if (config.hasPreprocessorPackage) {
return config.loadPreprocessorPackage();
} else {
return require;
}
})
.invoke("async", translatorId)
.then(function (translate) {
module.type = "js";
return translate(module);
});
}
})
.then(function () {
if (module.type === "js" && module.text !== void 0 && module.dependencies === void 0) {
// Remove the shebang
module.text = module.text.replace(/^#!/, "//#!");
// Parse dependencies.
module.dependencies = config.parseDependencies(module.text);
}
// Run optional optimizers.
// {text, type} to {text', type')
if (config.hasPreprocessorPackage && has.call(config.optimizers, module.type)) {
var optimizerId = config.optimizers[module.type];
return config.loadPreprocessorPackage()
.invoke("async", optimizerId)
.then(function (optimize) {
return optimize(module);
});
}
})
.then(function () {
if (
module.factory === void 0 &&
module.redirect === void 0 &&
module.exports === void 0
) {
// Then apply configured compilers. module {text, type} to
// {dependencies, factory || exports || redirect}
if (has.call(config.compilers, module.type)) {
var compilerId = Identifier.resolve(config.compilers[module.type], "");
return deepLoad(compilerId, "", loading)
.then(function () {
var compile = require(compilerId);
compile(module);
});
} else if (module.type === "js") {
config.compile(module);
}
}
// Final dependency massaging
var dependencies = module.dependencies = module.dependencies || [];
if (module.redirect !== void 0) {
dependencies.push(module.redirect);
}
if (module.extraDependencies !== void 0) {
Array.prototype.push.apply(module.dependencies, module.extraDependencies);
}
});
});
// Load a module definition, and the definitions of its transitive
// dependencies
function deepLoad(topId, viaId, loading) {
var module = getModuleDescriptor(topId);
// this is a memo of modules already being loaded so we don’t
// data-lock on a cycle of dependencies.
// has this all happened before? will it happen again?
loading = loading || {};
if (has.call(loading, topId)) {
return Q(); // break the cycle of violence.
}
loading[topId] = true; // this has happened before
return load(topId, viaId)
.then(function () {
// load the transitive dependencies using the magic of
// recursion.
var dependencies = module.dependencies = module.dependencies || [];
return Q.all(module.dependencies.map(function (depId) {
depId = Identifier.resolve(depId, topId);
// create dependees set, purely for debug purposes
var module = getModuleDescriptor(depId);
var dependees = module.dependees = module.dependees || {};
dependees[topId] = true;
return deepLoad(depId, topId, loading);
}));
}, function (error) {
module.error = error;
});
}
function lookup(topId, viaId) {
topId = Identifier.resolve(topId, viaId);
var module = getModuleDescriptor(topId);
// check for consistent case convention
if (module.id !== topId) {
throw new Error(
"Can't require module " + JSON.stringify(module.id) +
" by alternate spelling " + JSON.stringify(topId)
);
}
// handle redirects
if (module.redirect !== void 0) {
return lookup(module.redirect, topId);
}
// handle cross-package linkage
if (module.mappingRedirect !== void 0) {
return module.mappingRequire.lookup(module.mappingRedirect, "");
}
return module;
}
// Initializes a module by executing the factory function with a new
// module "exports" object.
function getExports(topId, viaId) {
var module = getModuleDescriptor(topId);
// check for consistent case convention
if (module.id !== topId) {
throw new Error(
"Can't require module " + JSON.stringify(module.id) +
" by alternate spelling " + JSON.stringify(topId)
);
}
// check for load error
if (module.error) {
var error = module.error;
error.message = (
"Can't require module " + JSON.stringify(module.id) +
" via " + JSON.stringify(viaId) +
" in " + JSON.stringify(config.name || config.location) +
" because " + error.message
);
throw error;
}
// handle redirects
if (module.redirect !== void 0) {
return getExports(module.redirect, viaId);
}
// handle cross-package linkage
if (module.mappingRedirect !== void 0) {
return module.mappingRequire(module.mappingRedirect, viaId);
}
// do not reinitialize modules
if (module.exports !== void 0) {
return module.exports;
}
// do not initialize modules that do not define a factory function
if (module.factory === void 0) {
throw new Error(
"Can't require module " + JSON.stringify(topId) +
" via " + JSON.stringify(viaId) + " " + JSON.stringify(module) +
" because no factory was or exports were created by the module loader configuration"
);
}
module.directory = URL.resolve(module.location, "./"); // EXTENSION
module.exports = {};
// Execute the factory function:
var returnValue = module.factory.call(
// in the context of the module: