forked from wayfind/flex-combo
/
flex-combo.js
576 lines (524 loc) · 20.6 KB
/
flex-combo.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
var http = require('http')
, fs = require('fs')
, path = require('path')
, isUtf8 = require('is-utf8')
, iconv = require('iconv-lite')
, joinbuffers = require('joinbuffers')
, mkdirp = require('mkdirp')
, crypto = require('crypto')
, beautify = require('./beautify.js').js_beautify
, util = require('util')
, mime = require('mime')
, juicer = require('juicer')
, less = require('less')
, sass = require('node-sass');
var debug = require('debug')('flex-combo:debug');
var debugInfo = require('debug')('flex-combo:info');
var green = '\u001b[32m';
var red = '\u001b[31m';
var blue = '\u001b[34m';
var gray = '\u001b[37m';
var yellow = '\u001b[33m';
var reset = '\u001b[0m';
var method_body = [
"var __escapehtml = {",
"escapehash: {",
"'<': '<',",
"'>': '>',",
"'&': '&',",
"'\"': '"',",
"\"'\": ''',",
"'/': '/'",
"},",
"escapereplace: function(k) {",
"return __escapehtml.escapehash[k];",
"},",
"escaping: function(str) {",
"return typeof(str) !== 'string' ? str : str.replace(/[&<>\"]/igm, this.escapereplace);",
"},",
"detection: function(data) {",
"return typeof(data) === 'undefined' ? '' : data;",
"}",
"};",
"var __throw = function(error) {",
"if(typeof(console) !== 'undefined') {",
"if(console.warn) {",
"console.warn(error);",
"return;",
"}",
"if(console.log) {",
"console.log(error);",
"return;",
"}",
"}",
"throw(error);",
"};",
"_method = _method || {};",
"_method.__escapehtml = __escapehtml;",
"_method.__throw = __throw;"
].join('');
function cosoleResp(type, c){
if(type == "Need"){
console.log('%s=>Need : %s%s%s %s',green, reset, blue, c, reset);
return;
}
if(type == 'Not found'){
console.log('%s<=Not found: %s%s%s %s',red, reset, gray, c, reset);
return;
}
if(type == 'Actually'){
console.log('%s Actually: %s%s%s %s',green, reset, gray, c, reset);
return;
}
if(type == 'Remote'){
console.log('%s<=Remote : %s%s%s %s',green, reset, gray, c, reset);
return;
}
if(type == 'Cache'){
console.log('%s<=Cache : %s%s%s %s',green, reset, gray, c, reset);
return;
}
console.log(green+'<='+type+': ' + reset + gray + ' ' + c + ' ' + reset);
return;
}
/**
Yahoo Combo:
<script src="http://yui.yahooapis.com/combo
?2.5.2/build/editor/editor-beta-min.js
&2.5.2/build/yahoo-dom-event/yahoo-dom-event.js
&2.5.2/build/container/container_core-min.js
&2.5.2/build/menu/menu-min.js
&2.5.2/build/element/element-beta-min.js
&2.5.2/build/button/button-min.js">
</script>
//淘宝combo server规则a.tbcdn.cn/apps??
*/
var param = {
urls: {},
host : 'assets.taobaocdn.com',
servlet : '?',
seperator: ',',
charset: 'gbk',
filter : {
'\\?.+':'',
'-min\\.js$':'.js',
'-min\\.css$':'.css'
},
supportedFile: '\\.js|\\.css|\\.png|\\.gif|\\.jpg|\\.swf|\\.xml|\\.less|\\.svg|\\.ttf|\\.mp3',
prjDir: '',
urlBasedCharset:{},
fns:[],
hosts:{'a.tbcdn.cn':'122.225.67.241', 'g.tbcdn.cn':'115.238.23.250'}
};
function adaptCharset(buff, outCharset, charset){
if (charset === outCharset) {
return buff;
}
return iconv.encode(iconv.decode(buff, charset), outCharset);
}
function filterUrl(url){
var filter = param.filter;
var filtered = url;
for(var fk in filter){
filtered = filtered.replace(new RegExp(fk), filter[fk]);
}
if(param.fns){
param.fns.forEach(function(fn){
try{
filtered = fn(filtered);
}
catch(e){
}
});
}
cosoleResp('Actually', filtered);
return filtered;
}
function isBinFile(fileName){
fileName = fileName.split('?')[0];
return !/.js$|.css$|.less$/.test(fileName);
}
/*
* 根据传入的返回最长匹配的目录映射
*/
function longgestMatchedDir(fullPath) {
fullPath = fullPath.split('?')[0];
var map = param.urls;
var longestMatchNum = -1 , longestMatchPos = null;
for (k in map) {
if (fullPath.replace(/\\/g, '/').indexOf(k) === 0 && longestMatchNum < k.length) {
longestMatchNum = k.length;
longestMatchPos = k;
}
}
return longestMatchPos;
}
/*
* 根据一个文件的全路径(如:/xxx/yyy/aa.js)从本地文件系统获取内容
*/
function readFromLocal (fullPath) {
fullPath = fullPath.split('?')[0];
var longestMatchPos = longgestMatchedDir(fullPath);
if(!longestMatchPos){ return null }
//找到最长匹配的配置,顺序遍历已定义好的目录。多个目录用逗号","分隔。
var map = param.urls;
var dirs = map[longestMatchPos].split(',');
for (var i = 0, len = dirs.length; i < len; i++){
var dir = dirs[i];
var revPath = fullPath.slice(longestMatchPos.length, fullPath.length);
var absPath = '';
//如果是绝对路径,直接使用
if(dir.indexOf('/') === 0 || /^\w{1}:\\.*$/.test(dir)){
absPath = path.normalize(path.join(dir, revPath));
}
else{
absPath = path.normalize(path.join(param.prjDir, dir, revPath));
}
//前后端模板一致化,如果是*.html.js格式的请求,并且js文件不存在,则编译*.html为juicer的function格式返回
var extName = path.extname(absPath);
var htmlName = absPath.slice(0, absPath.length - extName.length);
if(path.extname(htmlName).toLowerCase() === '.html' && fs.existsSync(htmlName)){
var buff = fs.readFileSync(htmlName);
var charset = isUtf8(buff) ? 'utf8' : 'gbk';
var tpl = iconv.decode(buff, charset);
var compiled = juicer(tpl)._render.toString().replace(/^function anonymous[^{]*?{([\s\S]*?)}$/igm, function($, fn_body) {
return 'function(_, _method) {' + method_body + fn_body + '};\n';
});
//允许为某个url特别指定编码
var outputCharset = param.charset;
if(param.urlBasedCharset && param.urlBasedCharset[longestMatchPos]){
outputCharset = param.urlBasedCharset[longestMatchPos];
}
var tempalteFunction = 'window["'+revPath+'"] = ' + compiled;
cosoleResp('Local Juicer Compile', htmlName);
fs.writeFile(absPath, tempalteFunction);
return iconv.encode(tempalteFunction, outputCharset);
}
// added by jayli
// 新增less文件解析
if(/\.less\.css$/i.test(absPath) && !fs.existsSync(absPath)){
var buff = fs.readFileSync(absPath.replace(/\.css$/i,''));
var charset = isUtf8(buff) ? 'utf8' : 'gbk';
var fContent = iconv.decode(buff, charset);
return new(less.Parser)({
processImports:false
}).parse(fContent,function(e,tree){
return tree.toCSS();
});
}
// added by liuhuo.gk
// 新增scss文件解析
if(/\.scss\.css$/i.test(absPath) && !fs.existsSync(absPath)){
var buff = fs.readFileSync(absPath.replace(/\.css$/i,''));
var charset = isUtf8(buff) ? 'utf8' : 'gbk';
var fContent = iconv.decode(buff, charset);
var css = sass.renderSync({
data: fContent,
outputStyle: 'compressed'
});
return css;
}
if(fs.existsSync(absPath)){
var buff = fs.readFileSync(absPath);
if(isBinFile(absPath)){
cosoleResp('Local', absPath);
return buff;
}
var charset = isUtf8(buff) ? 'utf8' : 'gbk';
//允许为某个url特别指定编码
var outputCharset = param.charset;
if(param.urlBasedCharset && param.urlBasedCharset[longestMatchPos]){
outputCharset = param.urlBasedCharset[longestMatchPos];
}
cosoleResp('Local', absPath);
return adaptCharset(buff, outputCharset, charset);
}
}
return null;
}
var merge = function(dest, src) {
for (var i in src) {
if(src[i] === Object(src[i])){
if(!dest[i]){
dest[i] = {};
}
merge(dest[i], src[i]);
continue;
}
dest[i] = src[i];
}
return dest;
}
var cacheFile = function(fullPath, content, encode){
var absPath = path.join(param.cacheDir, fullPath);
var lastDir = path.dirname(absPath);
if(/[<>\*\?]+/g.test(absPath)){
debugInfo('Exception file name: can not cache to %s',absPath);
return;
}
if(!fs.existsSync(lastDir)){
debug('%s is not exist',lastDir);
mkdirp(lastDir, function(){
fs.writeFileSync(absPath, content);
});
return;
}
debug('保存缓存%s', fullPath);
fs.writeFileSync(absPath, content);
}
var readFromCache = function(url, fullPath){
var absPath = path.join(param.cacheDir, fullPath);
if(fs.existsSync(absPath)){
var buff = fs.readFileSync(absPath);
if(isBinFile(absPath)){
cosoleResp('Cache', absPath);
return buff;
}
var charset = isUtf8(buff) ? 'utf8' : 'gbk';
//允许为某个url特别指定编码
var outputCharset = param.charset;
var longestMatchPos = longgestMatchedDir(url);
if(longestMatchPos){
if(param.urlBasedCharset && param.urlBasedCharset[longestMatchPos]){
outputCharset = param.urlBasedCharset[longestMatchPos];
}
}
cosoleResp('Cache', absPath);
return adaptCharset(buff, outputCharset, charset);
}
return null;
}
function buildRequestOption(url, req) {
var requestOption = {host: param.host, port: 80, path: url};
//处理IP加Request Header的情况
if (param.hostIp && param.headers) {
requestOption.host = param.hostIp;
requestOption.headers = param.headers;
}
if (param.hosts) {
for (hostName in param.hosts) {
if (req.headers.host == hostName) {
requestOption.host = param.hosts[hostName];
if (!requestOption.headers) {
requestOption.headers = {};
}
requestOption.headers.host = hostName;
break;
}
}
}
return requestOption;
}
exports = module.exports = function(prjDir, urls, options){
var userHome = process.env.HOME || process.env.USERPROFILE ||process.env.HOMEPATH;//兼容windows
var cacheDir = path.join(userHome, '.flex-combo/cache');
if(!fs.existsSync(cacheDir)){
mkdirp(cacheDir);
}
var userConfigPath = path.join(userHome, '.flex-combo/config.json');
if(!fs.existsSync(userConfigPath)){
if(!fs.existsSync(path.join(userHome,'.flex-combo'))){
mkdirp.sync(path.join(userHome,'.flex-combo'));
}
fs.writeFileSync(userConfigPath, beautify(JSON.stringify(param)));
}
else{
var paramStr = fs.readFileSync(userConfigPath);
paramStr.toString().replace(/[\n\r]/g, '');
param = merge(param, JSON.parse(paramStr));
}
param.cacheDir = cacheDir;
if(urls){
param.urls = merge(param.urls, urls);
}
if(options){
options.urls = param.urls;
param = merge(param, options);
}
param.prjDir = prjDir;
debug(util.inspect(param));
var fileReg = new RegExp(param.supportedFile);
return function(req, res, next) {
//远程请求的域名不能和访问域名一致,否则会陷入请求循环。
if(req.headers.host === param.host){
return;
}
var url = req.url.replace(/http:\/\/.+?\//,'/');//兼容windows,windows平台下取得的req.url带http://部分
var prefix = url.indexOf(param.servlet + '?');
//不包含combo的servlet,认为是单一文件
if(prefix === -1){
//combo不处理html文件,但是需要接管其他资源
if(!fileReg.test(url)) {
next();
return;
}
cosoleResp('Need', url);
var filteredUrl = filterUrl(url);
res.setHeader('Content-Type', mime.lookup(filteredUrl.split('?')[0]));
var singleFileContent = readFromLocal(filteredUrl);
if(singleFileContent){
res.end(singleFileContent);
return;
}
var fileName = crypto.createHash('md5').update(req.headers.host+url).digest('hex');
var cachedFile = readFromCache(filteredUrl, fileName);
if(cachedFile){
res.end(cachedFile);
return;
}
//本地没有,从服务器获取
var requestOption = buildRequestOption(url, req);
http.get(requestOption, function(resp) {
var buffs = [];
if(resp.statusCode !== 200){
var headerHost = '';
if(requestOption.headers && requestOption.headers.host)
{
headerHost = requestOption.headers.host;
}
cosoleResp('Not found', requestOption.host + requestOption.path + ' (host:'+ reset + yellow + headerHost + reset + ')');
res.writeHead(404);
res.end('File ' + requestOption.host + requestOption.path + ' not found.');
return;
}
resp.on('data', function(chunk) {
buffs.push(chunk);
});
resp.on('end', function() {
var buff = joinbuffers(buffs);
//fix 80% situation bom problem.quick and dirty
if(buff[0] === 239 && buff[1] === 187 && buff[2] === 191) {
buff = buff.slice(3, buff.length);
}
if(isBinFile(filteredUrl)){
var binfileName = crypto.createHash('md5').update(req.headers.host+requestOption.path).digest('hex');
cacheFile(binfileName, buff);
cosoleResp('Remote', requestOption.host + requestOption.path);
res.end(buff);
return;
}
cosoleResp('Remote', requestOption.host + requestOption.path);
var charset = isUtf8(buff) ? 'utf8' : 'gbk';
var longestMatchPos = longgestMatchedDir(filteredUrl);
//允许为某个url特别指定编码
var outputCharset = param.charset;
if(longestMatchPos){
if(param.urlBasedCharset && param.urlBasedCharset[longestMatchPos]){
outputCharset = param.urlBasedCharset[longestMatchPos];
}
}
var singleFileContent = adaptCharset(buff, outputCharset, charset);
var fileName = crypto.createHash('md5').update(req.headers.host+url).digest('hex');
cacheFile(fileName, buff, charset);
res.end(singleFileContent );
return;
});
}).on('error',function(e){
debugInfo('Networking error:' + e.message);
res.writeHead(404, { 'Content-Type': 'text/html;charset=utf-8'});
res.end('404 Error, File not found.');
return;
});
return;
}
cosoleResp('Need', url);
prefix = url.substring(0, prefix);
var files = url.substring(prefix.length + param.servlet.length + 1, url.length);
files = files.split(param.seperator, 1000);
var reqArray = [];
var prevNeedHttp = false ;//为循环做准备,用来判定上次循环的file是否需要通过http获取
var needHttpGet = '';
for(var i = 0, len = files.length; i < len; i++){
var file = files[i];
//combo URL有时候会多一个逗号
if(file === "") continue;
var fullPath = prefix + filterUrl(files[i]);
if(i === 0 ){
res.setHeader('Content-Type', mime.lookup(fullPath.split('?')[0]));
}
var fileContent = readFromLocal(fullPath);
if(!fileContent){
if(prevNeedHttp){
needHttpGet += ',' + file;
continue;
}
prevNeedHttp = true;
needHttpGet = file;
continue;
}
if(prevNeedHttp){
reqArray.push({file: needHttpGet, ready: false});
}
prevNeedHttp = false;
reqArray.push({file: file, content: fileContent, ready: true});
}
if(prevNeedHttp){
reqArray.push({file: needHttpGet, ready:false});
}
var reqPath = prefix + param.servlet + '?';
for(var i = 0, len = reqArray.length; i < len; i++){
if(reqArray[i].ready){
continue;
}
var cacheName = crypto.createHash('md5').update(req.headers.host+reqArray[i].file).digest('hex');
var cachedContent = readFromCache(reqArray[i].file, '/' + cacheName);
if(cachedContent){
reqArray[i].content = cachedContent;
reqArray[i].ready = true;
continue;
}
(function(id) {
var requestPath = reqPath + reqArray[id].file;
var requestOption = buildRequestOption(requestPath, req);
http.get(requestOption, function(resp) {
if(resp.statusCode !== 200){
var headerHost = '';
if(requestOption.headers && requestOption.headers.host)
{
headerHost = requestOption.headers.host;
}
cosoleResp('Not found', requestOption.host + reqPath + reqArray[id].file + '('+ yellow +'host:'+ headerHost + reset +')');
reqArray[id].ready = true;
reqArray[id].content = 'File '+ reqArray[id].file +' not found.';
sendData();
return;
}
var buffs = [];
resp.on('data', function(chunk) {
buffs.push(chunk);
});
resp.on('end', function() {
cosoleResp('Remote', requestOption.host + reqPath + reqArray[id].file);
reqArray[id].ready = true;
var buff = joinbuffers(buffs);
//fix 80% situation bom problem.quick and dirty
if(buff[0] === 239 && buff[1] === 187 && buff[2] === 191) {
buff = buff.slice(3, buff.length);
}
var fileName = crypto.createHash('md5').update(req.headers.host+reqArray[id].file).digest('hex');
var charset = isUtf8(buff) ? 'utf8' : 'gbk';
reqArray[id].content = adaptCharset(buff, param.charset, charset);
cacheFile('/' + fileName, buff, charset);
sendData();
});
}).on('error',function(e){
reqArray[id].ready = true;
debug('Networking error:' + e.message);
});
})(i);
}
var sendData = function(){
for(var j = 0, len = reqArray.length; j < len; j++){
if(reqArray[j].ready === false){
return;
}
}
reqArray.forEach(function(reqNode){
res.write(reqNode.content);
});
res.end();
}
//如果全部都在本地可以获取到,就立即返回内容给客户端
sendData();
}
}