-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransform.js
268 lines (234 loc) · 10.2 KB
/
transform.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
var fs = require('fs');
var path = require('path');
var util = require('util');
var through = require('through');
var falafel = require('falafel');
var unparse = require('escodegen').generate;
var minimatch = require('minimatchify');
var bindShim = "var bind = function bind(fn){ var args = Array.prototype.slice.call(arguments, 1); return function(){ var onearg = args.shift(); var newargs = args.concat(Array.prototype.slice.call(arguments,0)); var returnme = fn.apply(onearg, newargs ); return returnme; }; };";
module.exports = function (file) {
if (/\.json$/.test(file)) return through();
var data = '';
var foldNames = {};
var vars = [ '__dirname' ];
var dirname = path.dirname(file);
var pending = 0;
var tr = through(write, end);
return tr;
function containsUndefinedVariable (node) {
if (node.type === 'Identifier') {
if (vars.indexOf(node.name) === -1) {
return true;
}
}
else if (node.type === 'BinaryExpression') {
return containsUndefinedVariable(node.left)
|| containsUndefinedVariable(node.right)
;
}
else {
return false;
}
};
function write (buf) { data += buf }
function end () {
try { var output = parse() }
catch (err) {
this.emit('error', new Error(
err.toString().replace('Error: ', '') + ' (' + file + ')')
);
}
if (pending === 0) finish(output);
}
function finish (output) {
tr.queue(String(output));
tr.queue(null);
}
function parse () {
var output = falafel(data, function (node) {
var args = node.arguments;
var check;
if(isRequire(node)){
if(args[0] && args[0].value === 'foldify'){
check = true;
}
else if(args[0]){
try{
check = require.resolve(dirname + '/' + eval(unparse(args[0])));
check = check.split(path.sep);
var check2 = check.slice(check.indexOf("foldify")+1)
check = check2.length === 1;
}catch(e){}
}
}
if (isRequire(node) && check
&& node.parent.type === 'VariableDeclarator'
&& node.parent.id.type === 'Identifier') {
foldNames[node.parent.id.name] = true;
}
if (isRequire(node) && check
&& node.parent.type === 'AssignmentExpression'
&& node.parent.left.type === 'Identifier') {
foldNames[node.parent.left.name] = true;
}
if (!isFold(node) || containsUndefinedVariable(args[0])) return;
var thisDir = unparse(args[0]);
if(/^'\.\//.test(thisDir) || /^'\.\.\//.test(thisDir)){
thisDir = thisDir
.replace(/^'\.\//, "__dirname +'/")
.replace(/^'\.\.\//, "__dirname + '/../' +'/")
.replace(/ \+'\/'$/, "");
}
var thisDirParsed = eval(thisDir),
fpath = path.normalize( Function(vars, 'return ' + thisDir)(dirname) ),
thisOpts = args[1] ? eval("(" + unparse(args[1]) + ")") : {},
encoding = thisOpts.encoding || thisOpts.enc || "utf-8",
obj = "",
existingProps = [],
separator,
resolved,
parts,
files = [];
if(typeof thisOpts !== "object"){
return tr.emit('error', 'foldify (browserify) second argument must be an options object');
}
var toString = thisOpts.output && thisOpts.output.toLowerCase() === "string",
toArray = thisOpts.output && thisOpts.output.toLowerCase() === "array";
try{
if(~thisDirParsed.indexOf("/"))
separator = "/";
if(~thisDirParsed.indexOf("\\"))
separator = "\\";
parts = thisDirParsed.split(separator);
resolved = path.dirname( require.resolve( parts[0] + separator + 'package.json' ) );
if(!~resolved.indexOf("node_modules")) throw "not a node module";
fpath = resolved + path.sep + parts.slice(1).join(separator);
}catch(err){}
obj+= "((function(){ ";
obj+= bindShim;
if(toString){
obj+= "var returnMe = '';";
}
else if(toArray){
obj+= "var returnMe = [];";
}else{
obj+= "var fold = require('foldify'), proxy = {}, map = false;";
obj+= thisOpts.tree ? "map = {};" : "";
obj+= "var returnMe = bind( fold, {foldStatus: true, map: map}, proxy);";
}
function recurs(dirname2){
fs.readdirSync(dirname2).forEach(function(file){
var filepath = path.join( dirname2, file);
if(path.extname(file) === ''){
if(thisOpts.recursive || thisOpts.tree) recurs(filepath);
return
}
files.push(filepath);
});
}
recurs(fpath);
if(thisOpts.whitelist) files = whitelist(thisOpts.whitelist, files, path.resolve(fpath) );
if(thisOpts.blacklist) files = blacklist(thisOpts.blacklist, files, path.resolve(fpath) );
files.forEach(function(filepath){
var ext = path.extname(filepath),
name = path.basename(filepath, ext),
filename = name + ext,
isJs = ext === ".js" || ext === ".json",
propname;
if( toString ){
obj += "returnMe += " + JSON.stringify(fs.readFileSync(filepath, encoding)) + ";";
return
}
if( toArray ){
obj += "returnMe.push( " + JSON.stringify(fs.readFileSync(filepath, encoding)) + ");";
return
}
if((isJs && thisOpts.jsToString) || !isJs)
toRequire = JSON.stringify(fs.readFileSync(filepath, encoding));
else
toRequire = "require("+JSON.stringify(filepath)+")";
if(!thisOpts.includeExt && (isJs || thisOpts.includeExt === false) )
propname = JSON.stringify(name);
else
propname = JSON.stringify(filename);
if(thisOpts.fullPath || ~existingProps.indexOf(propname) )
propname = filepath;
else
existingProps.push(propname);
if(thisOpts.tree){
var paths = path.relative(fpath, filepath).split(path.sep);
obj+="var paths = " + JSON.stringify(paths) + ";";
obj+="var last, thismap;";
obj+="for(var x = 0, len = paths.length; x<len; x++){";
obj+="if(x===0){";
obj+="if(!returnMe[ paths[x] ] )";
obj+="returnMe[ paths[x] ] = {};";
obj+="last = returnMe[ paths[x] ];";
obj+="if(!map[ paths[x] ] )";
obj+="map[ paths[x] ] = {};";
obj+="thismap = map[ paths[x] ]";
obj+="}else if(x < (len-1)){";
obj+="if(!last[ paths[x] ] )";
obj+="last[ paths[x] ] = {};";
obj+="last = last[paths[x]];";
obj+="if(!thismap[ paths[x] ] )";
obj+="thismap[ paths[x] ] = {};";
obj+="thismap = thismap[ paths[x] ];";
obj+="}else{";
obj+="last[ " + propname + " ] = " + toRequire + ";";
obj+="thismap[ " + propname + " ] = true;";
obj+="}";
obj+="}";
}else{
obj += "returnMe[" + propname + "] = " + toRequire + ";";
}
});
if(!toString && !toArray)
obj+= "for(var p in returnMe){ proxy[p] = returnMe[p]; }";
obj += "return returnMe;})())";
node.update(obj);
tr.emit('file', fpath);
});
return output;
}
function isFold (node) {
if (!node) return false;
if (node.type !== 'CallExpression') return false;
return node.callee.type === 'Identifier' && foldNames[node.callee.name];
}
function whitelist(whitelist, files, rootdir){
if(!whitelist || !files) return
rootdir = rootdir || "";
var output = [];
whitelist = util.isArray(whitelist) ? whitelist : [whitelist];
whitelist.forEach(function(rule){
rule = path.join( rootdir, rule );
files.forEach( function(name){
if(~output.indexOf(name)) return
if( minimatch(name, rule) )
output.push(name);
})
});
return output;
}
function blacklist(blacklist, files, rootdir){
if(!blacklist || !files) return
blacklist = util.isArray(blacklist) ? blacklist : [blacklist];
rootdir = rootdir || "";
files = files.filter(function(name){
return !blacklist.some(function(rule){
rule = path.join( rootdir, rule );
return minimatch(name, rule);
});
});
return files
}
};
function isRequire (node) {
var c = node.callee;
return c
&& node.type === 'CallExpression'
&& c.type === 'Identifier'
&& c.name === 'require'
;
}