-
Notifications
You must be signed in to change notification settings - Fork 5
/
tinypack.ts
187 lines (154 loc) · 4.41 KB
/
tinypack.ts
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
import {
readFileSync as readFile,
writeFileSync as writeFile,
statSync as stat,
existsSync as exists
} from "fs";
import { resolve, dirname } from "path";
import * as ts from "typescript";
function error(msg: string): any {
console.error(msg);
process.exit(1);
}
let input = process.argv[2];
if (!input) error("No input is provided.");
let isFile = (path: string) => exists(path) && stat(path).isFile();
let isDir = (path: string) => exists(path) && stat(path).isDirectory();
function localModulePath(path: string, from?: string): string {
let absPath = from ? resolve(dirname(from), path) : resolve(path);
let tsPath = absPath.endsWith(".ts") ? absPath : absPath + ".ts";
let indexPath = resolve(absPath, "index.ts");
return isFile(tsPath) ? tsPath :
isDir(absPath) && isFile(indexPath) ? indexPath :
error(`Cannot find module '${path}'.`);
}
function npmModulePath(pkg: string, from: string): string {
let projRoot = dirname(from);
while (!isDir(resolve(projRoot, "node_modules"))) {
projRoot = dirname(projRoot);
}
let pkgRoot = resolve(projRoot, "node_modules", pkg);
let jsPath = pkgRoot + ".js";
if (isFile(jsPath)) {
return jsPath;
}
let packageJSONPath = resolve(pkgRoot, "package.json");
if (isFile(packageJSONPath)) {
let main: string = require(packageJSONPath).module ||
require(packageJSONPath).main;
if (main) {
return resolve(pkgRoot, main);
}
}
let indexPath = resolve(pkgRoot, "index.js");
if (isFile(indexPath)) {
return indexPath;
}
return error(`Cannot find module '${pkg}'.`);
}
let entryFile = localModulePath(input);
/*
* STEP 1: Type check
*/
let diagnostics = ts.getPreEmitDiagnostics(
ts.createProgram([entryFile], {
strict: true,
target: ts.ScriptTarget.Latest,
moduleResolution: ts.ModuleResolutionKind.NodeJs
})
);
if (diagnostics.length) {
diagnostics.forEach(d => console.log(d.messageText));
error("Errors.");
}
/*
* STEP 2: Compile modules
*/
type Module = {
id: number;
file: string;
deps: Map<string, number>;
transpiled: string;
}
let moduleID = 0;
let fileModuleIdMap = new Map([[entryFile, moduleID]]);
let files = [entryFile];
function compile(file: string): Module {
let id = fileModuleIdMap.get(file)!;
let deps = new Map<string, number>();
let content = readFile(file, "utf-8");
let source = ts.createSourceFile(file, content, ts.ScriptTarget.ES2015);
source.forEachChild(node => {
if (node.kind === ts.SyntaxKind.ImportDeclaration) {
let importDecl = node as ts.ImportDeclaration;
// module specifier should be a string literal
let moduleSpecifier = importDecl.moduleSpecifier.getText(source);
let dep = JSON.parse(moduleSpecifier) as string;
let depPath: string;
if (dep.startsWith(".")) {
depPath = localModulePath(dep, file);
} else {
depPath = npmModulePath(dep, file);
}
let depID = fileModuleIdMap.get(depPath);
if (depID === undefined) {
depID = ++moduleID;
fileModuleIdMap.set(depPath, depID);
files.push(depPath);
}
deps.set(dep, depID);
}
});
let transpiled = ts.transpileModule(content, {
compilerOptions: {
target: ts.ScriptTarget.ES5,
module: ts.ModuleKind.CommonJS,
noImplicitUseStrict: true,
pretty: true
}
}).outputText;
return { id, file, deps, transpiled };
}
let modules: Array<Module> = [];
let file;
while (file = files.shift()) {
modules.push(compile(file));
}
/*
* STEP 3: Code generation
*/
function* generate(modules: Array<Module>): Iterable<string> {
yield ";(function (modules) {";
yield `
var executedModules = {};
(function executeModule(id) {
if (executedModules[id]) return executedModules[id];
var mod = modules[id];
var localRequire = function (path) {
return executeModule(mod[1][path]);
};
var module = { exports: {} };
executedModules[id] = module.exports;
mod[0](localRequire, module, module.exports);
return module.exports;
})(0);
`;
yield "})({";
for (let mod of modules) {
yield `${mod.id}: [`;
yield `function (require, module, exports) {`;
yield mod.transpiled;
yield "}, {";
for (let [key, val] of mod.deps) {
yield `${JSON.stringify(key)}: ${val},`
}
yield "}"
yield "],";
}
yield "})";
}
let result: string = "";
for (let code of generate(modules)) {
result += code + "\n";
}
console.log(result);