This repository has been archived by the owner on Feb 26, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
shadow.js
112 lines (97 loc) · 2.37 KB
/
shadow.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
/**
* @license MIT http://troopjs.mit-license.org/
*/
define([ "text" ], function (text) {
"use strict";
/**
* RequireJS shadow plugin
* @class requirejs.shadow
* @static
* @alias plugin.requirejs
*/
//TODO Add usage docs
var UNDEFINED;
var EXPORTS = "exports";
var EXTENSION = ".js";
var PATTERN = /(.+?)#(.+)$/;
var RE_EMPTY = /^empty:/;
var REQUIRE_VERSION = require.version;
var buildMap = {};
function amdify (scriptText, hashVal) {
var pattern = /([^=&]+)=([^&]+)/g;
var m;
var deps = [];
var args = [];
while (hashVal && (m = pattern.exec(hashVal))) {
if (m[1] === EXPORTS) {
scriptText += ";\nreturn " + m[2] + ";\n";
}
else {
deps.push("'" + m[2] + "'");
args.push(m[1]);
}
}
return "define([" + deps.join(", ") + "], function (" + args.join(", ") + ") {\n"
+ scriptText
+ "});";
}
function cmpVersion(a, b) {
var result;
var len;
var i;
a = a.split(".");
b = b.split(".");
len = Math.min(a.length, b.length);
for (i = 0; i < len; i++) {
result = parseInt(a[i], null) - parseInt(b[i], null);
if (result !== 0) {
return result;
}
}
return a.length - b.length;
}
return {
load : function (name, req, onLoad, config) {
var m;
var hashVal;
var content;
var url;
var realName = name;
// The name is like 'jquery.form#$=jquery&exports=$',
// So, if macthed, m[1] is 'jquery.form', m[2] is '$=jquery&exports=$'
if ((m = PATTERN.exec(name))) {
realName = m[1];
hashVal = m[2];
}
url = req.toUrl(realName + EXTENSION);
// For Optimization. The url is "empty:" if excluded.
if (RE_EMPTY.test(url)) {
onLoad(UNDEFINED);
}
else {
text.get(url, function(data) {
content = amdify(data, hashVal);
if (config.isBuild) {
buildMap[name] = content;
}
onLoad.fromText(name, content);
// On requirejs version below '2.1.0',
// need to manually require the module after the call to onLoad.fromText()
if (cmpVersion(REQUIRE_VERSION, "2.1.0") < 0) {
req([ name ], onLoad);
}
});
}
},
write : function (pluginName, moduleName, write) {
var content;
if (moduleName in buildMap) {
content = buildMap[moduleName];
content = content.replace(/define\(/, function (match) {
return match + '"' + [pluginName, moduleName].join('!') + '",';
});
write(content);
}
}
};
});