-
Notifications
You must be signed in to change notification settings - Fork 2
/
kernel.js
708 lines (627 loc) · 19.6 KB
/
kernel.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
(function () {
/*!
require-kernel
Created by Chad Weider on 01/04/11.
Released to the Public Domain on 17/01/12.
*/
/* Storage */
var main = null; // Reference to main module in `modules`.
var modules = {}; // Repository of module objects build from `definitions`.
var definitions = {}; // Functions that construct `modules`.
var loadingModules = {}; // Locks for detecting circular dependencies.
var definitionWaiters = {}; // Locks for clearing duplicate requires.
var fetchRequests = []; // Queue of pending requests.
var currentRequests = 0; // Synchronization for parallel requests.
var maximumRequests = 2; // The maximum number of parallel requests.
var deferred = []; // A list of callbacks that can be evaluated eventually.
var deferredScheduled = false; // If deferred functions will be executed.
var syncLock = undefined;
var globalKeyPath = undefined;
var rootURI = undefined;
var libraryURI = undefined;
var libraryLookupComponent = undefined;
var JSONP_TIMEOUT = 60 * 1000;
function CircularDependencyError(message) {
this.name = "CircularDependencyError";
this.message = message;
};
CircularDependencyError.prototype = Error.prototype;
function ArgumentError(message) {
this.name = "ArgumentError";
this.message = message;
};
ArgumentError.prototype = Error.prototype;
/* Utility */
function hasOwnProperty(object, key) {
// Object-independent because an object may define `hasOwnProperty`.
return Object.prototype.hasOwnProperty.call(object, key);
}
/* Deferral */
function defer(f_1, f_2, f_n) {
deferred.push.apply(deferred, arguments);
}
function _flushDefer() {
// Let exceptions happen, but don't allow them to break notification.
try {
while (deferred.length) {
var continuation = deferred.shift();
continuation();
}
deferredScheduled = false;
} finally {
deferredScheduled = deferred.length > 0;
deferred.length && setTimeout(_flushDefer, 0);
}
}
function flushDefer() {
if (!deferredScheduled && deferred.length > 0) {
if (syncLock) {
// Only asynchronous operations will wait on this condition so schedule
// and don't interfere with the synchronous operation in progress.
deferredScheduled = true;
setTimeout(_flushDefer, 0);
} else {
_flushDefer();
}
}
}
function flushDeferAfter(f) {
try {
deferredScheduled = true;
f();
deferredScheduled = false;
flushDefer();
} finally {
deferredScheduled = false;
deferred.length && setTimeout(flushDefer, 0);
}
}
// See RFC 2396 Appendix B
var URI_EXPRESSION =
/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
function parseURI(uri) {
var match = uri.match(URI_EXPRESSION);
var location = match && {
scheme: match[2],
host: match[4],
path: match[5],
query: match[7],
fragment: match[9]
};
return location;
}
function joinURI(location) {
var uri = "";
if (location.scheme)
uri += location.scheme + ':';
if (location.host)
uri += "//" + location.host
if (location.host && location.path && location.path.charAt(0) != '/')
url += "/"
if (location.path)
uri += location.path
if (location.query)
uri += "?" + location.query
if (uri.fragment)
uri += "#" + location.fragment
return uri;
}
function isSameDomain(uri) {
var host_uri =
(typeof location == "undefined") ? {} : parseURI(location.toString());
var uri = parseURI(uri);
return (!uri.scheme && !uri.host)
|| (uri.scheme === host_uri.scheme) && (uri.host === host_uri.host);
}
function mirroredURIForURI(uri) {
var host_uri =
(typeof location == "undefined") ? {} : parseURI(location.toString());
var uri = parseURI(uri);
uri.scheme = host_uri.scheme;
uri.host = host_uri.host;
return joinURI(uri);
}
function normalizePath(path) {
var pathComponents1 = path.split('/');
var pathComponents2 = [];
var component;
for (var i = 0, ii = pathComponents1.length; i < ii; i++) {
component = pathComponents1[i];
switch (component) {
case '':
if (i == 0 || i == ii - 1) {
// This indicates a leading or trailing slash.
pathComponents2.push(component);
}
break;
case '.':
// Always skip.
break;
case '..':
if (pathComponents2.length > 1
|| (pathComponents2.length == 1
&& pathComponents2[0] != ''
&& pathComponents2[0] != '.')) {
pathComponents2.pop();
break;
}
default:
pathComponents2.push(component);
}
}
return pathComponents2.join('/');
}
function fullyQualifyPath(path, basePath) {
var fullyQualifiedPath = path;
if (path.charAt(0) == '.'
&& (path.charAt(1) == '/'
|| (path.charAt(1) == '.' && path.charAt(2) == '/'))) {
if (!basePath) {
basePath = '';
} else if (basePath.charAt(basePath.length-1) != '/') {
basePath += '/';
}
fullyQualifiedPath = basePath + path;
}
return fullyQualifiedPath;
}
function setRootURI(URI) {
if (!URI) {
throw new ArgumentError("Invalid root URI.");
}
rootURI = (URI.charAt(URI.length-1) == '/' ? URI.slice(0,-1) : URI);
}
function setLibraryURI(URI) {
libraryURI = (URI.charAt(URI.length-1) == '/' ? URI : URI + '/');
}
function setLibraryLookupComponent(component) {
component = component && component.toString();
if (!component) {
libraryLookupComponent = undefined;
} else if (component.match(/\//)) {
throw new ArgumentError("Invalid path component.");
} else {
libraryLookupComponent = component;
}
}
// If a `libraryLookupComponent` is defined, then library modules should
// be looked at in every parent directory (roughly).
function searchPathsForModulePath(path, basePath) {
path = normalizePath(path);
// Should look for nearby libarary modules.
if (path.charAt(0) != '/' && libraryLookupComponent) {
var paths = [];
var components = basePath.split('/');
while (components.length > 1) {
if (components[components.length-1] == libraryLookupComponent) {
components.pop();
}
var searchPath = normalizePath(fullyQualifyPath(
'./'+libraryLookupComponent+'/' + path, components.join('/') + '/'
));
paths.push(searchPath);
components.pop();
}
paths.push(path);
return paths;
} else {
return [normalizePath(fullyQualifyPath(path, basePath))];
}
}
function URIForModulePath(path) {
var components = path.split('/');
for (var i = 0, ii = components.length; i < ii; i++) {
components[i] = encodeURIComponent(components[i]);
}
path = components.join('/')
if (path.charAt(0) == '/') {
if (!rootURI) {
throw new Error("Attempt to retrieve the root module "
+ "\""+ path + "\" but no root URI is defined.");
}
return rootURI + path;
} else {
if (!libraryURI) {
throw new Error("Attempt to retrieve the library module "
+ "\""+ path + "\" but no libary URI is defined.");
}
return libraryURI + path;
}
}
function _compileFunction(code, filename) {
return new Function(code);
}
function compileFunction(code, filename) {
var compileFunction = rootRequire._compileFunction || _compileFunction;
return compileFunction.apply(this, arguments);
}
/* Remote */
function setRequestMaximum (value) {
value == parseInt(value);
if (value > 0) {
maximumRequests = value;
checkScheduledfetchDefines();
} else {
throw new ArgumentError("Value must be a positive integer.")
}
}
function setGlobalKeyPath (value) {
globalKeyPath = value;
}
var XMLHttpFactories = [
function () {return new XMLHttpRequest()},
function () {return new ActiveXObject("Msxml2.XMLHTTP")},
function () {return new ActiveXObject("Msxml3.XMLHTTP")},
function () {return new ActiveXObject("Microsoft.XMLHTTP")}
];
function createXMLHTTPObject() {
var xmlhttp = false;
for (var i = 0, ii = XMLHttpFactories.length; i < ii; i++) {
try {
xmlhttp = XMLHttpFactories[i]();
} catch (error) {
continue;
}
break;
}
return xmlhttp;
}
function getXHR(uri, async, callback, request) {
var request = request || createXMLHTTPObject();
if (!request) {
throw new Error("Error making remote request.")
}
function onComplete(request) {
// Build module constructor.
if (request.status == 200) {
callback(undefined, request.responseText);
} else {
callback(true, undefined);
}
}
request.open('GET', uri, !!(async));
if (async) {
request.onreadystatechange = function (event) {
if (request.readyState == 4) {
onComplete(request);
}
};
request.send(null);
} else {
request.send(null);
onComplete(request);
}
}
function getXDR(uri, callback) {
var xdr = new XDomainRequest();
xdr.open('GET', uri);
xdr.error(function () {
callback(true, undefined);
});
xdr.onload(function () {
callback(undefined, request.responseText);
});
xdr.send();
}
function fetchDefineXHR(path, async) {
// If cross domain and request doesn't support such requests, go straight
// to mirroring.
var _globalKeyPath = globalKeyPath;
var callback = function (error, text) {
if (error) {
define(path, null);
} else {
if (_globalKeyPath) {
compileFunction(text, path)();
} else {
var definition = compileFunction(
'return (function (require, exports, module) {'
+ text + '\n'
+ '})', path)();
define(path, definition);
}
}
}
var uri = URIForModulePath(path);
if (_globalKeyPath) {
uri += '?callback=' + encodeURIComponent(globalKeyPath + '.define');
}
if (isSameDomain(uri)) {
getXHR(uri, async, callback);
} else {
var request = createXMLHTTPObject();
if (request && request.withCredentials !== undefined) {
getXHR(uri, async, callback, request);
} else if (async && (typeof XDomainRequest != "undefined")) {
getXDR(uri, callback);
} else {
getXHR(mirroredURIForURI(uri), async, callback);
}
}
}
function fetchDefineJSONP(path) {
var head = document.head
|| document.getElementsByTagName('head')[0]
|| document.documentElement;
var script = document.createElement('script');
if (script.async !== undefined) {
script.async = "true";
} else {
script.defer = "true";
}
script.type = "application/javascript";
script.src = URIForModulePath(path)
+ '?callback=' + encodeURIComponent(globalKeyPath + '.define');
// Handle failure of JSONP request.
if (JSONP_TIMEOUT < Infinity) {
var timeoutId = setTimeout(function () {
timeoutId = undefined;
define(path, null);
}, JSONP_TIMEOUT);
definitionWaiters[path].unshift(function () {
timeoutId === undefined && clearTimeout(timeoutId);
});
}
head.insertBefore(script, head.firstChild);
}
/* Modules */
function fetchModule(path, continuation) {
if (hasOwnProperty(definitionWaiters, path)) {
definitionWaiters[path].push(continuation);
} else {
definitionWaiters[path] = [continuation];
schedulefetchDefine(path);
}
}
function schedulefetchDefine(path) {
fetchRequests.push(path);
checkScheduledfetchDefines();
}
function checkScheduledfetchDefines() {
if (fetchRequests.length > 0 && currentRequests < maximumRequests) {
var fetchRequest = fetchRequests.pop();
currentRequests++;
definitionWaiters[fetchRequest].unshift(function () {
currentRequests--;
checkScheduledfetchDefines();
});
if (globalKeyPath
&& typeof document !== 'undefined'
&& document.readyState
&& /^loaded|complete$/.test(document.readyState)) {
fetchDefineJSONP(fetchRequest);
} else {
fetchDefineXHR(fetchRequest, true);
}
}
}
function fetchModuleSync(path, continuation) {
fetchDefineXHR(path, false);
continuation();
}
function moduleIsLoaded(path) {
return hasOwnProperty(modules, path);
}
function loadModule(path, continuation) {
// If it's a function then it hasn't been exported yet. Run function and
// then replace with exports result.
if (!moduleIsLoaded(path)) {
if (hasOwnProperty(loadingModules, path)) {
throw new CircularDependencyError("Encountered circular dependency.");
} else if (!moduleIsDefined(path)) {
throw new Error("Attempt to load undefined module.");
} else if (definitions[path] === null) {
continuation(null);
} else {
var definition = definitions[path];
var _module = {id: path, exports: {}};
var _require = requireRelativeTo(path);
if (!main) {
main = _module;
}
try {
loadingModules[path] = true;
definition(_require, _module.exports, _module);
modules[path] = _module;
delete loadingModules[path];
continuation(_module);
} finally {
delete loadingModules[path];
}
}
} else {
var module = modules[path];
continuation(module);
}
}
function _moduleAtPath(path, fetchFunc, continuation) {
var suffixes = ['', '.js', '/index.js'];
if (path.charAt(path.length - 1) == '/') {
suffixes = ['index.js'];
}
var i = 0, ii = suffixes.length;
var _find = function (i) {
if (i < ii) {
var path_ = path + suffixes[i];
var after = function () {
loadModule(path_, function (module) {
if (module === null) {
_find(i + 1);
} else {
continuation(module);
}
});
}
if (!moduleIsDefined(path_)) {
fetchFunc(path_, after);
} else {
after();
}
} else {
continuation(null);
}
};
_find(0);
}
function moduleAtPath(path, continuation) {
defer(function () {
_moduleAtPath(path, fetchModule, continuation);
});
}
function moduleAtPathSync(path) {
var module;
var oldSyncLock = syncLock;
syncLock = true;
try {
_moduleAtPath(path, fetchModuleSync, function (_module) {
module = _module;
});
} finally {
syncLock = oldSyncLock;
}
return module;
}
/* Definition */
function moduleIsDefined(path) {
return hasOwnProperty(definitions, path);
}
function defineModule(path, module) {
if (typeof path != 'string'
|| !((typeof module == 'function') || module === null)) {
throw new ArgumentError(
"Definition must be a (string, function) pair.");
}
if (moduleIsDefined(path)) {
// Drop import silently
} else {
definitions[path] = module;
}
}
function defineModules(moduleMap) {
if (typeof moduleMap != 'object') {
throw new ArgumentError("Mapping must be an object.");
}
for (var path in moduleMap) {
if (hasOwnProperty(moduleMap, path)) {
defineModule(path, moduleMap[path]);
}
}
}
function define(fullyQualifiedPathOrModuleMap, module) {
var moduleMap;
if (arguments.length == 1) {
moduleMap = fullyQualifiedPathOrModuleMap;
defineModules(moduleMap);
} else if (arguments.length == 2) {
var path = fullyQualifiedPathOrModuleMap;
defineModule(fullyQualifiedPathOrModuleMap, module);
moduleMap = {};
moduleMap[path] = module;
} else {
throw new ArgumentError("Expected 1 or 2 arguments, but got "
+ arguments.length + ".");
}
// With all modules installed satisfy those conditions for all waiters.
for (var path in moduleMap) {
if (hasOwnProperty(moduleMap, path)
&& hasOwnProperty(definitionWaiters, path)) {
defer.apply(this, definitionWaiters[path]);
delete definitionWaiters[path];
}
}
flushDefer();
}
/* Require */
function _designatedRequire(path, continuation, relativeTo) {
var paths = searchPathsForModulePath(path, relativeTo);
if (continuation === undefined) {
var module;
for (var i = 0, ii = paths.length; i < ii && !module; i++) {
var path = paths[i];
module = moduleAtPathSync(path);
}
if (!module) {
throw new Error("The module at \"" + path + "\" does not exist.");
}
return module.exports;
} else {
if (!(typeof continuation == 'function')) {
throw new ArgumentError("Continuation must be a function.");
}
flushDeferAfter(function () {
function search() {
var path = paths.shift();
return moduleAtPath(path, function (module) {
if (module || paths.length == 0) {
continuation(module && module.exports);
} else {
search();
}
})
}
search();
});
}
}
function designatedRequire(path, continuation) {
var designatedRequire =
rootRequire._designatedRequire || _designatedRequire;
return designatedRequire.apply(this, arguments);
}
function requireRelative(basePath, qualifiedPath, continuation) {
qualifiedPath = qualifiedPath.toString();
var path = normalizePath(fullyQualifyPath(qualifiedPath, basePath));
return designatedRequire(path, continuation, basePath);
}
function requireRelativeN(basePath, qualifiedPaths, continuation) {
if (!(typeof continuation == 'function')) {
throw new ArgumentError("Final argument must be a continuation.");
} else {
// Copy and validate parameters
var _qualifiedPaths = [];
for (var i = 0, ii = qualifiedPaths.length; i < ii; i++) {
_qualifiedPaths[i] = qualifiedPaths[i].toString();
}
var results = [];
function _require(result) {
results.push(result);
if (qualifiedPaths.length > 0) {
requireRelative(basePath, qualifiedPaths.shift(), _require);
} else {
continuation.apply(this, results);
}
}
for (var i = 0, ii = qualifiedPaths.length; i < ii; i++) {
requireRelative(basePath, _qualifiedPaths[i], _require);
}
}
}
var requireRelativeTo = function (basePath) {
basePath = basePath.replace(/[^\/]+$/, '');
function require(qualifiedPath, continuation) {
if (arguments.length > 2) {
var qualifiedPaths = Array.prototype.slice.call(arguments, 0, -1);
var continuation = arguments[arguments.length-1];
return requireRelativeN(basePath, qualifiedPaths, continuation);
} else {
return requireRelative(basePath, qualifiedPath, continuation);
}
}
require.main = main;
return require;
}
var rootRequire = requireRelativeTo('/');
/* Private internals */
rootRequire._modules = modules;
rootRequire._definitions = definitions;
rootRequire._designatedRequire = _designatedRequire;
rootRequire._compileFunction = _compileFunction;
/* Public interface */
rootRequire.define = define;
rootRequire.setRequestMaximum = setRequestMaximum;
rootRequire.setGlobalKeyPath = setGlobalKeyPath;
rootRequire.setRootURI = setRootURI;
rootRequire.setLibraryURI = setLibraryURI;
rootRequire.setLibraryLookupComponent = setLibraryLookupComponent;
return rootRequire;
}())