-
Notifications
You must be signed in to change notification settings - Fork 0
/
amd-tree.js
72 lines (65 loc) · 2.31 KB
/
amd-tree.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
/* global -name*/
"use strict";
var mine = require("mine");
var pathJoin = require("pathjoin");
var binary = require('bodec');
var modes = require('js-git/lib/modes');
module.exports = amdTree;
function amdTree(servePath, req, callback) {
var path = pathJoin(req.paths.root, req.input, req.paths.local);
servePath(path, function (err, result) {
if (err) return callback(err);
if (!shouldHandle(path, result)) return callback();
return callback(null, {
mode: result.mode,
hash: result.hash + "-" + req.codeHash,
root: result.root,
fetch : fetch
});
function fetch(callback) {
result.fetch(function (err, value) {
if (err) return callback(err);
if (modes.isFile(result.mode)) {
return compile(path, value, callback);
}
if (result.mode === modes.tree) {
var tree = {};
Object.keys(value).forEach(function (key) {
var entry = value[key];
if (shouldHandle(key, entry)) {
entry.hash += "-" + req.codeHash;
tree[key] = entry;
}
});
value = tree;
}
return callback(null, value);
});
}
});
function shouldHandle(path, entry) {
return entry && (entry.mode === modes.tree ||
modes.isFile(entry.mode) && /\.js$/i.test(path));
}
function compile(path, blob, callback) {
var prefix = pathJoin(req.paths.rule, "..", req.base || ".");
var js = binary.toUnicode(blob);
var deps = mine(js);
var length = deps.length;
var paths = new Array(length);
var full = req.paths.full;
var localPath = prefix ? full.substring(prefix.length + 1) : full;
var base = localPath.substring(0, localPath.lastIndexOf("/"));
for (var i = length - 1; i >= 0; i--) {
var dep = deps[i];
var depPath = dep.name[0] === "." ? pathJoin(base, dep.name) : dep.name;
if (!(/\.[^\/]+$/.test(depPath))) depPath += ".js";
paths[i] = depPath;
js = js.substr(0, dep.offset) + depPath + js.substr(dep.offset + dep.name.length);
}
js = "define(" + JSON.stringify(localPath) + ", " +
JSON.stringify(paths) + ", function (module, exports) { " +
js + "\n});\n";
callback(null, binary.fromUnicode(js));
}
}