-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
212 lines (195 loc) · 5.64 KB
/
index.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
const { readFile } = require("./fs");
const { inspect } = require("./utils");
const dotenv = require("dotenv");
const { promisify } = require("util");
const path = require("path");
const { parse } = require("@babel/parser");
const traverse = require("@babel/traverse").default;
const types = require("@babel/types");
const { transformFromAstAsync } = require("@babel/core");
const resolve = promisify(require("resolve"));
const BUNDLE_ENV = "development";
// starts from 1 for easier conditions
let id = 1;
const files = new Map(); // path -> id
async function createAsset(rawFileName, forceCreate = false, env) {
const fileName = path.normalize(rawFileName);
if (!forceCreate && files.has(fileName)) return { id: files.get(fileName) };
const content = await readFile(fileName, "utf-8");
const ast = parse(content, {
sourceType: "module",
plugins: ["jsx"]
});
const dependencies = [];
const t = types;
traverse(ast, {
MemberExpression(path) {
if (
t.isMemberExpression(path.node.object) &&
path.node.object.property.name === "env"
) {
if (
t.isIdentifier(path.node.object.object) &&
path.node.object.object.name === "process"
)
if (t.isIdentifier(path.node.property))
path.replaceWith(
typeof env[path.node.property.name] === "string"
? t.stringLiteral(env[path.node.property.name])
: t.identifier("undefined")
);
}
}
});
traverse(ast, {
Conditional(path) {
const test = path.get("test");
const evaluate = test.evaluate();
if (!evaluate.confident) return;
const next = evaluate.value ? "consequent" : "alternate";
if (!path.node[next]) return path.remove();
path.replaceWith(path.node[next]);
}
});
traverse(ast, {
ImportDeclaration({ node }) {
dependencies.push(node.source.value);
},
CallExpression({ node }) {
const { callee, arguments } = node;
if (callee.name !== "require") return;
const [fileArgument] = arguments;
if (!fileArgument) throw new Error("No files were passed to require!");
if (fileArgument.type !== "StringLiteral")
throw new Error("Dynamic Require isn't currently supported");
dependencies.push(fileArgument.value);
}
});
const { code: transformed } = await transformFromAstAsync(ast, content, {
presets: [
[
"@babel/env",
{
targets: {
chrome: "70"
}
}
]
],
plugins: ["@babel/plugin-transform-react-jsx"]
});
const asset = {
id: files.get(fileName) || id++,
fileName,
content,
dependencies,
transformed
};
files.set(fileName, asset.id);
return asset;
}
async function createGraph(fileName, env) {
//console.log(fileName, path.normalize(fileName));
const asset = await createAsset(
await resolve(fileName, { basedir: "./" }),
true,
env
);
//console.log(asset);
const assets = [asset];
for (const asset of assets) {
const dir = path.dirname(asset.fileName);
asset.mapping = {};
for (const dep of asset.dependencies) {
const depFile = await resolve(dep, { basedir: dir });
const childAsset = await createAsset(depFile, false, env);
asset.mapping[dep] = childAsset.id;
// only newly createdAssets get sent to HMR
if (childAsset.transformed) assets.push(childAsset);
}
}
return assets;
}
let env = {};
async function bundle(entry) {
files.clear();
id = 1;
env = { NODE_ENV: BUNDLE_ENV };
try {
Object.assign(env, dotenv.parse(await readFile("./.env", "utf-8")));
} catch {}
try {
Object.assign(
env,
dotenv.parse(await readFile("./.env.development", "utf-8"))
);
} catch {}
const graph = await createGraph(entry, env);
const modules = graph
.map(
a => `
${a.id} : [function(require, module, exports){
${a.transformed}
},
${JSON.stringify(a.mapping)},
__kaito__exports
]
`
)
.join(",");
const result = `
var process = {env:${JSON.stringify(env)}};
var __kaito__exports = {};
var __kaito__modules = {${modules}};
var __kaito__require = function require(id) {
var [fn, mapping, exports] = __kaito__modules[id];
if(exports !== __kaito__exports) return exports;
function localRequire(localFileName) {
console.log(id, mapping[localFileName]);
return require(mapping[localFileName]);
}
var module = {exports:{}};
//__kaito__modules[id][2] = module.exports;
fn(localRequire, module, module.exports);
return __kaito__modules[id][2]= module.exports;
}
__kaito__require(1);
`;
return result;
}
async function bundleAsset(fileName) {
const assets = await createGraph(fileName, env);
return `
${assets
.map(
a => `
__kaito__modules[${a.id}] = [
function(require, module, exports){
${a.transformed}
},
${JSON.stringify(a.mapping)},
__kaito__exports
];
`
)
.join("")}
function __kaito__moduleInvalidate(id, leaf) {
console.log("invalidate",id, leaf);
if(id === leaf) return true;
var current = __kaito__modules[id];
var isLeafParent = false;
Object.values(current[1]).forEach(function(child) {
isLeafParent = isLeafParent || __kaito__moduleInvalidate(child, leaf);
});
if(isLeafParent) current[2] = __kaito__exports;
return isLeafParent;
}
__kaito__moduleInvalidate(1, ${assets[0].id});
console.log("HMR!");
__kaito__require(1);
`;
}
module.exports = {
bundle,
bundleAsset
};