-
Notifications
You must be signed in to change notification settings - Fork 0
/
naked.js
78 lines (63 loc) · 2.86 KB
/
naked.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
// Copyright © 2011 Barnesandnoble.com llc
// Released under the MIT License (see MIT-LICENSE.txt).
// NOTE: requires jQuery; we didn't want to implement XHR and promises ourselves.
(function () {
if (!module.constructor.prototype.load) {
throw new Error("The Modules/2.0 implementation in use does not support module provider plug-ins.");
}
// Maps ids to jQuery promises for loading that script.
var loadPromises = {};
// TODO: document requireRegExp and consider whether or not declareRegExp should be more like requireRegExp.
// Both from BravoJS: http://code.google.com/p/bravojs/source/browse/plugins/jquery-loader/jquery-loader.js
var declareRegExp = /(^|[\r\n])\s*module.declare\s*\(/;
var requireRegExp = /\/\/.*|\/\*[\s\S]*?\*\/|"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'|[;=(,:!^]\s*\/(?:\\.|[^\/\\])+\/|(?:^|\W)\s*require\s*\(\s*("(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*')\s*\)/g;
// Borrowed from BravoJS, which says "mostly borrowed from FlyScript."
function scrapeDependenciesFrom(rawSource) {
var dependencies = [];
var result = null;
while ((result = requireRegExp.exec(rawSource)) !== null) {
if (result[1]) {
dependencies.push(result[1]);
}
}
return dependencies;
}
// See http://blog.getfirebug.com/2009/08/11/give-your-eval-a-name-with-sourceurl/
function makeSourceUrlString(uri) {
return "\n//@ sourceURL=" + uri;
}
function makeSourceToEvalForWrapped(uri, rawSource) {
return rawSource + makeSourceUrlString(uri);
}
function makeSourceToEvalForNaked(uri, rawSource) {
var dependencies = scrapeDependenciesFrom(rawSource);
return "module.declare(["
+ dependencies.join(", ")
+ "], function (require, exports, module) {\n"
+ rawSource
+ "\n})"
+ makeSourceUrlString(uri);
}
function evalModule(rawSource, uri) {
if (rawSource.match(declareRegExp)) {
eval(makeSourceToEvalForWrapped(uri, rawSource));
} else {
eval(makeSourceToEvalForNaked(uri, rawSource));
}
}
module.constructor.prototype.load = function (moduleIdentifier, onModuleLoaded) {
var id = require.id(moduleIdentifier);
var uri = require.uri(id);
// Only do the loading once, but store a promise so that future calls to module.load execute the module.declare
// (as per the spec) and get their callbacks called.
if (!Object.prototype.hasOwnProperty.call(loadPromises, id)) {
loadPromises[id] = jQuery.ajax({ url: uri, dataType: "text" });
}
loadPromises[id]
.success(function (data) {
evalModule(data, uri);
onModuleLoaded();
})
.error(onModuleLoaded);
};
}());