forked from fred-wang/TeXZilla
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommonJS.js
252 lines (237 loc) · 8.88 KB
/
commonJS.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
/* -*- Mode: Javascript; indent-tabs-mode:nil; js-indent-level: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*jslint indent: 2 */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
////////////////////////////////////////////////////////////////////////////////
// Export the public API to commonJS programs.
////////////////////////////////////////////////////////////////////////////////
if (typeof require !== "undefined" && typeof exports !== "undefined") {
exports.setDOMParser = function (aDOMParser) {
TeXZilla.setDOMParser(aDOMParser);
};
exports.setXMLSerializer = function (aXMLSerializer) {
TeXZilla.setXMLSerializer(aXMLSerializer);
};
exports.setSafeMode = function (aEnable) {
TeXZilla.setSafeMode(aEnable);
};
exports.setItexIdentifierMode = function (aEnable) {
TeXZilla.setItexIdentifierMode(aEnable);
};
exports.getTeXSource = function () {
return TeXZilla.getTeXSource.apply(TeXZilla, arguments);
};
exports.toMathMLString = function () {
return TeXZilla.toMathMLString.apply(TeXZilla, arguments);
};
exports.toMathML = function () {
return TeXZilla.toMathML.apply(TeXZilla, arguments);
};
exports.toImage = function () {
return TeXZilla.toImage.apply(TeXZilla, arguments);
};
exports.filterString = function () {
return TeXZilla.filterString.apply(TeXZilla, arguments);
};
exports.filterElement = function () {
return TeXZilla.filterElement.apply(TeXZilla, arguments);
};
}
////////////////////////////////////////////////////////////////////////////////
// Export the command-line API to commonJS programs.
////////////////////////////////////////////////////////////////////////////////
if (typeof require !== "undefined") {
// FIXME: This tries to work with slimerjs, phantomjs and nodejs. Ideally,
// we should have a standard commonJS interface.
// https://github.com/fred-wang/TeXZilla/issues/6
var exitCommonJS = function (aStatus) {
if (typeof process !== "undefined") {
process.exit(aStatus);
} else if (typeof slimer !== "undefined") {
slimer.exit(aStatus);
} else if (typeof phantom !== "undefined") {
phantom.exit(aStatus);
}
};
var usage = function () {
// Display the usage information.
console.log("\nUsage:\n");
console.log("commonjs TeXZilla.js [help]");
console.log(" Print this help message.\n");
console.log("commonjs TeXZilla.js parser aTeX [aDisplay] [aRTL] [aThrowExceptionOnError]");
console.log(" Print TeXZilla.toMathMLString(aTeX, aDisplay, aRTL, aThrowExceptionOnError)");
console.log(" The interpretation of arguments and the default values are the same.\n");
console.log("commonjs TeXZilla.js webserver [port] [safe] [itexId]");
console.log(" Start a Web server on the specified port (default:3141)");
console.log(" See the TeXZilla wiki for details.\n");
console.log("cat input | commonjs TeXZilla.js streamfilter [safe] [itexId] > output");
console.log(" Make TeXZilla behaves as a stream filter. The TeX fragments are");
console.log(" converted into MathML.");
console.log(" See the TeXZilla wiki for details.\n");
console.log(" where commonjs is slimerjs, nodejs or phantomjs.");
};
var setParamValue = function (aParam, aKey, aString) {
// Set the param value from the string value.
if (aKey === "tex") {
aParam[aKey] = aString;
} else if (aKey === "display" || aKey === "rtl" || aKey === "exception" ||
aKey === "safe" || aKey === "itexId") {
aParam[aKey] = (aString === "true");
}
};
var getMathMLString = function (aParam) {
// Call the TeXZilla parser with the specified parameters and
// return the MathML output.
return TeXZilla.toMathMLString(aParam.tex, aParam.display,
aParam.rtl, aParam.exception);
};
var getParametersFromURL = function (aURL) {
// Get the param values from the GET URL.
var param, query, vars, i, pair, key, value;
param = {};
query = aURL.split("?")[1];
if (query) {
vars = query.split("&");
for (i = 0; i < vars.length; i++) {
pair = vars[i].split("=");
key = decodeURIComponent(pair[0]).toLowerCase();
value = decodeURIComponent(pair[1]);
setParamValue(param, key, value);
}
}
return param;
};
var getParametersFromPOSTData = function (aPOSTData) {
// Get the param values from the POST JSON data.
var param = {}, json = JSON.parse(aPOSTData), key;
for (key in json) {
setParamValue(param, key, json[key]);
}
return param;
};
var getServerResponseFromParam = function (aParam) {
// Get the JSON data to send back.
var data = { tex: aParam.tex };
try {
data.mathml = getMathMLString(aParam);
data.exception = null;
} catch (e) {
data.exception = e.message;
}
return JSON.stringify(data);
};
var webserverListener = function (aRequest, aResponse) {
// Listener for the "webserver" module (phantomjs, slimerjs).
var param = {}, json = {}, response;
if (aRequest.method === "GET") {
param = getParametersFromURL(aRequest.url);
} else if (aRequest.method === "POST") {
param = getParametersFromPOSTData(aRequest.post);
}
if (param.tex !== undefined) {
json = getServerResponseFromParam(param);
}
response = JSON.stringify(json);
aResponse.statusCode = 200;
aResponse.setHeader("Content-Type", "application/json");
aResponse.write(response);
aResponse.close();
};
var httpListener = function (aRequest, aResponse) {
// Listener for the "http" module (nodejs).
var param = {}, json = {}, response, body = "";
aRequest.setEncoding("utf8");
aRequest.on("data", function (aChunk) {
body += aChunk;
});
aRequest.on("end", function () {
aResponse.writeHead(200, {"Content-Type": ""});
if (aRequest.method === "GET") {
param = getParametersFromURL(aRequest.url);
} else if (aRequest.method === "POST") {
param = getParametersFromPOSTData(body);
}
if (param.tex !== undefined) {
json = getServerResponseFromParam(param);
}
response = JSON.stringify(json);
aResponse.writeHead(200, { "Content-Type": "application/json" });
aResponse.write(response);
aResponse.end();
});
};
var startWebServer = function (aPort)
{
try {
require("webserver").create().listen(aPort, webserverListener);
} catch (e) {
require("http").createServer(httpListener).listen(aPort);
}
console.log("Web server started on http://localhost:" + aPort);
}
var main = function (aArgs, aStdinContent) {
// Main command line function.
var param = {};
if (aArgs.length >= 3 && aArgs[1] === "parser") {
// Parse the string and print the output.
setParamValue(param, "tex", aArgs[2]);
setParamValue(param, "display", aArgs[3]);
setParamValue(param, "rtl", aArgs[4]);
setParamValue(param, "exception", aArgs[5]);
try {
console.log(getMathMLString(param));
exitCommonJS(0);
} catch (e) {
console.log(e);
exitCommonJS(1);
}
} else if (aArgs.length >= 2 && aArgs[1] === "webserver") {
setParamValue(param, "safe", aArgs[2]);
TeXZilla.setSafeMode(param.safe);
setParamValue(param, "itexId", aArgs[3]);
TeXZilla.setItexIdentifierMode(param.itexId);
// Run a Web server.
try {
startWebServer(aArgs.length >= 3 ? parseInt(aArgs[2], 10) : 3141);
} catch (e) {
console.log(e);
exitCommonJS(1);
}
} else if (aArgs.length >= 2 && aArgs[1] === "streamfilter") {
setParamValue(param, "safe", aArgs[2]);
TeXZilla.setSafeMode(param.safe);
setParamValue(param, "itexId", aArgs[3]);
TeXZilla.setItexIdentifierMode(param.itexId);
if (typeof process !== "undefined") {
var stdinContent = "";
process.stdin.resume();
process.stdin.setEncoding("utf-8");
process.stdin.on("data", function(aData) { stdinContent += aData; });
process.stdin.on("end", function() {
console.log(TeXZilla.filterString(stdinContent, true));
exitCommonJS(0);
});
} else {
// FIXME: Slimerjs does not seem to support stdin.
console.log(TeXZilla.
filterString(require("system").stdin.read(), true));
exitCommonJS(0);
}
} else {
usage();
exitCommonJS(0);
}
};
if (typeof exports === "undefined" ||
(typeof module !== "undefined" && require.main === module)) {
// Process the command line arguments, the stdin content and execute the
// main program.
if (typeof process !== "undefined") {
main(process.argv.slice(1));
} else {
main(require("system").args);
}
}
}