-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.ts
255 lines (205 loc) · 8.47 KB
/
index.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
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
import { spawn } from "child_process";
import { createHash } from "crypto";
import * as fs from "fs";
import * as path from "path";
import * as templates from "./templates";
/* tslint:disable-next-line */
const compile = require("node-elm-compiler").compile;
const renderDirName = ".elm-static-html";
export interface Options {
model?: any;
decoder?: string;
alreadyRun?: boolean;
elmMakePath?: string;
installMethod?: string;
indent?: number;
newLines?: boolean;
}
function makeCacheDir(dirPath: string) {
// make our cache dir
// ignore these and try to continue anyway
try {
fs.mkdirSync(dirPath);
} catch (e) {
if (e.code !== 'EEXIST' && !process.env.HIDE_WARNINGS) console.log(`Failed to make ${dirPath}/Native due to`, e);
}
try {
fs.mkdirSync(path.join(dirPath, "Native"));
} catch (e) {
if (e.code !== 'EEXIST' && !process.env.HIDE_WARNINGS) console.log(`Failed to make ${dirPath}/Native due to`, e);
}
}
function parseProjectName(repoName: string): string {
return repoName
.replace("https://github.com/", "")
.replace(".git", "")
.replace("/", "$");
}
function runElmApp(moduleHash: string, dirPath: string, filenamesAndModels: any[][]): Promise<Output[]> {
return new Promise((resolve, reject) => {
const Elm = require(path.join(dirPath, "elm.js"));
const privateName = `PrivateMain${moduleHash}`;
if (Object.keys(Elm).indexOf(privateName) === - 1) {
return reject("Code generation problem: Unable to find the module: " + privateName);
}
const elmApp = Elm[privateName].worker(filenamesAndModels);
elmApp.ports[`htmlOut${moduleHash}`].subscribe(resolve);
});
}
function wipeElmFromCache(dirPath: string) {
try {
const resolved = require.resolve(path.join(dirPath, "elm.js"));
delete require.cache[resolved];
} catch (e) {
// ignore if we didn't have elm in the require cache
}
}
function installPackages(dirPath: string, installMethod?: string) {
return new Promise((resolve, reject) => {
if (installMethod) {
const runningProcess = spawn(installMethod, [], { cwd: dirPath });
runningProcess.on("close", resolve);
} else {
resolve();
}
});
}
function makeHash(viewFunction: string): string {
return createHash("MD5").update(viewFunction).digest("hex");
}
export interface ViewFunctionConfig {
viewFunction: string;
fileOutputName: string;
model?: any;
decoder?: string;
indent?: number;
newLines?: boolean;
}
export interface Output {
generatedHtml: string;
fileOutputName: string;
}
// compiles multiple view functions into one elm file
// which is much faster if you're likely to need all of them
export function multiple(
rootDir: string, configs: ViewFunctionConfig[],
alreadyRun?: boolean, elmMakePath?: string, installMethod?: string): Promise<Output[]> {
// the modulehash is the hash of all view functions concated
const moduleHash = makeHash(configs.map((config) => config.viewFunction).join(""));
const dirPath = path.join(rootDir, renderDirName);
if (alreadyRun === true) {
const filenamesAndModels = configs.map((config) => [config.fileOutputName, config.model]);
return runElmApp(moduleHash, dirPath, filenamesAndModels);
}
// try to load elm-package.json
const originalElmPackagePath = path.join(rootDir, "elm-package.json");
let elmPackage: any = null;
try {
elmPackage = JSON.parse(fs.readFileSync(originalElmPackagePath, "utf8"));
} catch (e) {
return Promise.reject(`Failed to load ${originalElmPackagePath}`);
}
makeCacheDir(dirPath);
wipeElmFromCache(dirPath);
const projectName = parseProjectName(elmPackage.repository);
elmPackage = fixElmPackage(rootDir, elmPackage);
const elmPackagePath = path.join(dirPath, "elm-package.json");
const privateMainPath = path.join(dirPath, `PrivateMain${moduleHash}.elm`);
const nativePath = path.join(dirPath, "Native/Jsonify.js");
fs.writeFileSync(elmPackagePath, JSON.stringify(elmPackage));
const templateConfigs = configs.map((config) => { return {
decoder: config.decoder,
indent: config.indent,
model: config.model,
newLines: config.newLines,
viewFunction: config.viewFunction,
viewHash: makeHash(config.viewFunction)};
},
);
const rendererFileContents = templates.generateRendererFile(moduleHash, templateConfigs);
fs.writeFileSync(privateMainPath, rendererFileContents);
const nativeString = templates.generateNativeModuleString(projectName);
fs.writeFileSync(nativePath, nativeString);
return installPackages(dirPath, installMethod).then(() => {
return runCompiler(moduleHash, privateMainPath, dirPath, configs, elmMakePath);
});
}
export function elmStaticHtml(rootDir: string, viewFunction: string, options: Options): Promise<string> {
const viewHash = makeHash(viewFunction);
const config = { decoder: options.decoder,
fileOutputName: "placeholder",
indent: options.indent,
model: options.model,
newLines: options.newLines,
viewFunction,
viewHash,
};
const dirPath = path.join(rootDir, renderDirName);
if (options.alreadyRun === true) {
return runElmApp(viewHash, dirPath, [[config.fileOutputName, options.model]])
.then((outputs) => outputs[0].generatedHtml);
}
// try to load elm-package.json
const originalElmPackagePath = path.join(rootDir, "elm-package.json");
let elmPackage: any = null;
try {
elmPackage = JSON.parse(fs.readFileSync(originalElmPackagePath, "utf8"));
} catch (e) {
return Promise.reject(`Failed to load ${originalElmPackagePath}`);
}
makeCacheDir(dirPath);
wipeElmFromCache(dirPath);
const projectName = parseProjectName(elmPackage.repository);
elmPackage = fixElmPackage(rootDir, elmPackage);
const elmPackagePath = path.join(dirPath, "elm-package.json");
const privateMainPath = path.join(dirPath, `PrivateMain${viewHash}.elm`);
const nativePath = path.join(dirPath, "Native/Jsonify.js");
fs.writeFileSync(elmPackagePath, JSON.stringify(elmPackage));
const rendererFileContents = templates.generateRendererFile(viewHash, [config]);
fs.writeFileSync(privateMainPath, rendererFileContents);
const nativeString = templates.generateNativeModuleString(projectName);
fs.writeFileSync(nativePath, nativeString);
return installPackages(dirPath, options.installMethod).then(() => {
return runCompiler(viewHash, privateMainPath, dirPath, [config], options.elmMakePath)
.then((results) => results[0].generatedHtml);
});
}
function fixElmPackage(workingDir: string, elmPackage: any) {
elmPackage["native-modules"] = true;
const sources = elmPackage["source-directories"].map((dir: string) => {
return path.join(workingDir, dir);
});
sources.push(".");
elmPackage["source-directories"] = sources;
elmPackage.dependencies["eeue56/elm-html-in-elm"] = "2.0.0 <= v < 3.0.0";
return elmPackage;
}
function runCompiler(moduleHash: string,
privateMainPath: string,
rootDir: string,
configs: ViewFunctionConfig[], elmMakePath?: string): Promise<Output[]> {
const options: any = {
cwd: rootDir,
output: "elm.js",
yes: true,
};
if (elmMakePath) {
options.pathToMake = elmMakePath;
}
return new Promise((resolve, reject) => {
fs.readdir(rootDir, (err, files) => {
const actualFiles = files.filter((name) => name.indexOf("PrivateMain") === 0);
const compileProcess = compile(actualFiles, options);
compileProcess.on("exit",
(exitCode: number) => {
if (exitCode !== 0) {
return reject(exitCode);
}
const runs = runElmApp(moduleHash, rootDir,
configs.map((config) => [config.fileOutputName, config.model]));
return runs.then(resolve);
},
);
});
});
}