-
Notifications
You must be signed in to change notification settings - Fork 0
/
helper.js
346 lines (284 loc) · 10.7 KB
/
helper.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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
'use strict';
const fs = require('fs');
const vm = require('vm');
const v8 = require('v8');
const path = require('path');
const Module = require('module');
const fork = require('child_process').fork;
v8.setFlagsFromString('--no-lazy');
if (Number.parseInt(process.versions.node, 10) >= 12) {
v8.setFlagsFromString('--no-flush-bytecode'); // Thanks to A-Parser (@a-parser)
}
const COMPILED_EXTNAME = '.jsc';
/**
* Generates v8 bytecode buffer.
* @param {string} javascriptCode JavaScript source that will be compiled to bytecode.
* @returns {Buffer} The generated bytecode.
*/
const compileCode = function (javascriptCode) {
if (typeof javascriptCode !== 'string') {
throw new Error(`javascriptCode must be string. ${typeof javascriptCode} was given.`);
}
const script = new vm.Script(javascriptCode, {
produceCachedData: true
});
const bytecodeBuffer = (script.createCachedData && script.createCachedData.call)
? script.createCachedData()
: script.cachedData;
return bytecodeBuffer;
};
/**
* This function runs the compileCode() function (above)
* via a child process usine Electron as Node
* @param {string} javascriptCode
* @returns {Promise<Buffer>} - returns a Promise which resolves in the generated bytecode.
*/
const compileElectronCode = function (javascriptCode) {
return new Promise((resolve, reject) => {
let data = Buffer.from([]);
const electronPath = path.join(path.dirname(require.resolve('electron')), 'cli.js');
if (!fs.existsSync(electronPath)) {
throw new Error('Electron not installed');
}
const bytenodePath = path.join(__dirname, 'cli.js');
// create a subprocess in which we run Electron as our Node and V8 engine
// running Bytenode to compile our code through stdin/stdout
const proc = fork(electronPath, [bytenodePath, '--compile', '--no-module', '-'], {
env: { ELECTRON_RUN_AS_NODE: '1' },
stdio: ['pipe', 'pipe', 'pipe', 'ipc']
});
if (proc.stdin) {
proc.stdin.write(javascriptCode);
proc.stdin.end();
}
if (proc.stdout) {
proc.stdout.on('data', (chunk) => {
data = Buffer.concat([data, chunk]);
});
proc.stdout.on('error', (err) => {
console.error(err);
});
proc.stdout.on('end', () => {
resolve(data);
});
}
if (proc.stderr) {
proc.stderr.on('data', (chunk) => {
console.error('Error: ', chunk.toString());
});
proc.stderr.on('error', (err) => {
console.error('Error: ', err);
});
}
proc.addListener('message', (message) => console.log(message));
proc.addListener('error', err => console.error(err));
proc.on('error', (err) => reject(err));
proc.on('exit', () => { resolve(data); });
});
};
// TODO: rewrite this function
const fixBytecode = function (bytecodeBuffer) {
if (!Buffer.isBuffer(bytecodeBuffer)) {
throw new Error('bytecodeBuffer must be a buffer object.');
}
const dummyBytecode = compileCode('"ಠ_ಠ"');
if (process.version.startsWith('v8.8') || process.version.startsWith('v8.9')) {
// Node is v8.8.x or v8.9.x
dummyBytecode.slice(16, 20).copy(bytecodeBuffer, 16);
dummyBytecode.slice(20, 24).copy(bytecodeBuffer, 20);
} else if (process.version.startsWith('v12') ||
process.version.startsWith('v13') ||
process.version.startsWith('v14') ||
process.version.startsWith('v15') ||
process.version.startsWith('v16') ||
process.version.startsWith('v17') ||
process.version.startsWith('v18') ||
process.version.startsWith('v19')) {
dummyBytecode.slice(12, 16).copy(bytecodeBuffer, 12);
} else {
dummyBytecode.slice(12, 16).copy(bytecodeBuffer, 12);
dummyBytecode.slice(16, 20).copy(bytecodeBuffer, 16);
}
};
// TODO: rewrite this function
const readSourceHash = function (bytecodeBuffer) {
if (!Buffer.isBuffer(bytecodeBuffer)) {
throw new Error('bytecodeBuffer must be a buffer object.');
}
if (process.version.startsWith('v8.8') || process.version.startsWith('v8.9')) {
// Node is v8.8.x or v8.9.x
// eslint-disable-next-line no-return-assign
return bytecodeBuffer.slice(12, 16).reduce((sum, number, power) => sum += number * Math.pow(256, power), 0);
} else {
// eslint-disable-next-line no-return-assign
return bytecodeBuffer.slice(8, 12).reduce((sum, number, power) => sum += number * Math.pow(256, power), 0);
}
};
/**
* Runs v8 bytecode buffer and returns the result.
* @param {Buffer} bytecodeBuffer The buffer object that was created using compileCode function.
* @returns {any} The result of the very last statement executed in the script.
*/
const runBytecode = function (bytecodeBuffer) {
if (!Buffer.isBuffer(bytecodeBuffer)) {
throw new Error('bytecodeBuffer must be a buffer object.');
}
fixBytecode(bytecodeBuffer);
const length = readSourceHash(bytecodeBuffer);
let dummyCode = '';
if (length > 1) {
dummyCode = '"' + '\u200b'.repeat(length - 2) + '"'; // "\u200b" Zero width space
}
const script = new vm.Script(dummyCode, {
cachedData: bytecodeBuffer
});
if (script.cachedDataRejected) {
throw new Error('Invalid or incompatible cached data (cachedDataRejected)');
}
return script.runInThisContext();
};
/**
* Compiles JavaScript file to .jsc file.
* @param {object|string} args
* @param {string} args.filename The JavaScript source file that will be compiled
* @param {boolean} [args.compileAsModule=true] If true, the output will be a commonjs module
* @param {string} [args.output=filename.jsc] The output filename. Defaults to the same path and name of the original file, but with `.jsc` extension.
* @param {boolean} [args.electron=false] If true, compile code for Electron (which needs to be installed)
* @param {boolean} [args.createLoader=false] If true, create a loader file.
* @param {boolean} [args.loaderFilename='%.loader.js'] Filename or pattern for generated loader files. Defaults to originalFilename.loader.js. Use % as a substitute for originalFilename.
* @param {string} [output] The output filename. (Deprecated: use args.output instead)
* @returns {Promise<string>} A Promise which returns the compiled filename
*/
const compileFile = async function (args, output) {
let filename, compileAsModule, electron, createLoader, loaderFilename;
if (typeof args === 'string') {
filename = args;
compileAsModule = true;
electron = false;
createLoader = false;
} else if (typeof args === 'object') {
filename = args.filename;
compileAsModule = args.compileAsModule !== false;
electron = args.electron;
createLoader = args.createLoader;
loaderFilename = args.loaderFilename;
if (loaderFilename) createLoader = true;
}
if (typeof filename !== 'string') {
throw new Error(`filename must be a string. ${typeof filename} was given.`);
}
// @ts-ignore
const compiledFilename = args.output || output || filename.slice(0, -3) + COMPILED_EXTNAME;
if (typeof compiledFilename !== 'string') {
throw new Error(`output must be a string. ${typeof compiledFilename} was given.`);
}
const javascriptCode = fs.readFileSync(filename, 'utf-8');
let code;
if (compileAsModule) {
code = Module.wrap(javascriptCode.replace(/^#!.*/, ''));
} else {
code = javascriptCode.replace(/^#!.*/, '');
}
let bytecodeBuffer;
if (electron) {
bytecodeBuffer = await compileElectronCode(code);
} else {
bytecodeBuffer = compileCode(code);
}
fs.writeFileSync(compiledFilename, bytecodeBuffer);
if (createLoader) {
addLoaderFile(compiledFilename, loaderFilename);
}
return compiledFilename;
};
/**
* Runs .jsc file and returns the result.
* @param {string} filename
* @returns {any} The result of the very last statement executed in the script.
*/
const runBytecodeFile = function (filename) {
if (typeof filename !== 'string') {
throw new Error(`filename must be a string. ${typeof filename} was given.`);
}
const bytecodeBuffer = fs.readFileSync(filename);
console.log(bytecodeBuffer)
return runBytecode(bytecodeBuffer);
};
Module._extensions[COMPILED_EXTNAME] = function (fileModule, filename) {
const bytecodeBuffer = fs.readFileSync(filename);
fixBytecode(bytecodeBuffer);
const length = readSourceHash(bytecodeBuffer);
let dummyCode = '';
if (length > 1) {
dummyCode = '"' + '\u200b'.repeat(length - 2) + '"'; // "\u200b" Zero width space
}
const script = new vm.Script(dummyCode, {
filename: filename,
lineOffset: 0,
displayErrors: true,
cachedData: bytecodeBuffer
});
if (script.cachedDataRejected) {
throw new Error('Invalid or incompatible cached data (cachedDataRejected)');
}
/*
This part is based on:
https://github.com/zertosh/v8-compile-cache/blob/7182bd0e30ab6f6421365cee0a0c4a8679e9eb7c/v8-compile-cache.js#L158-L178
*/
function require (id) {
return fileModule.require(id);
}
require.resolve = function (request, options) {
// @ts-ignore
return Module._resolveFilename(request, fileModule, false, options);
};
if (process.mainModule) {
require.main = process.mainModule;
}
// @ts-ignore
require.extensions = Module._extensions;
// @ts-ignore
require.cache = Module._cache;
const compiledWrapper = script.runInThisContext({
filename: filename,
lineOffset: 0,
columnOffset: 0,
displayErrors: true
});
const dirname = path.dirname(filename);
const args = [fileModule.exports, require, fileModule, filename, dirname, process, global];
return compiledWrapper.apply(fileModule.exports, args);
};
/**
* Add a loader file for a given .jsc file
* @param {String} fileToLoad path of the .jsc file we're loading
* @param {String} loaderFilename - optional pattern or name of the file to write - defaults to filename.loader.js. Patterns: "%" represents the root name of .jsc file.
*/
const addLoaderFile = function (fileToLoad, loaderFilename) {
let loaderFilePath;
if (typeof loaderFilename === 'boolean' || loaderFilename === undefined || loaderFilename === '') {
loaderFilePath = fileToLoad.replace('.jsc', '.loader.js');
} else {
loaderFilename = loaderFilename.replace('%', path.parse(fileToLoad).name);
loaderFilePath = path.join(path.dirname(fileToLoad), loaderFilename);
}
const relativePath = path.relative(path.dirname(loaderFilePath), fileToLoad);
const code = loaderCode('./' + relativePath);
fs.writeFileSync(loaderFilePath, code);
};
const loaderCode = function (targetPath) {
return `
require('bytenode');
require('${targetPath}');
`;
};
global.bytenode = {
compileCode,
compileFile,
compileElectronCode,
runBytecode,
runBytecodeFile,
addLoaderFile,
loaderCode
};
module.exports = global.bytenode;