Skip to content

Commit ed7570f

Browse files
authored
Use dynamic require in asc.js without eval (AssemblyScript#1445)
1 parent 6df63c4 commit ed7570f

File tree

4 files changed

+51
-44
lines changed

4 files changed

+51
-44
lines changed

.eslintrc.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@ module.exports = {
1616
},
1717
globals: {
1818
"BigInt64Array": "readonly",
19-
"BigUint64Array": "readonly"
19+
"BigUint64Array": "readonly",
20+
"__non_webpack_require__": "readonly"
2021
},
2122

2223
// === General rules =========================================================

cli/asc.js

Lines changed: 43 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -41,28 +41,32 @@ const mkdirp = require("./util/mkdirp");
4141
const find = require("./util/find");
4242
const binaryen = global.binaryen || (global.binaryen = require("binaryen"));
4343

44+
const dynrequire = typeof __webpack_require__ === "function"
45+
? __non_webpack_require__
46+
: require;
47+
4448
const WIN = process.platform === "win32";
4549
const EOL = WIN ? "\r\n" : "\n";
4650
const SEP = WIN ? "\\" : "/";
4751

4852
// Sets up an extension with its definition counterpart and relevant regexes.
49-
function setupExtension(extension) {
50-
if (!extension.startsWith(".")) extension = "." + extension;
53+
function setupExtension(ext) {
54+
if (!ext.startsWith(".")) ext = "." + ext;
5155
return {
52-
ext: extension,
53-
ext_d: ".d" + extension,
54-
re: new RegExp("\\" + extension + "$"),
55-
re_d: new RegExp("\\.d\\" + extension + "$"),
56-
re_except_d: new RegExp("^(?!.*\\.d\\" + extension + "$).*\\" + extension + "$"),
57-
re_index: new RegExp("(?:^|[\\\\\\/])index\\" + extension + "$")
56+
ext,
57+
ext_d: ".d" + ext,
58+
re: new RegExp("\\" + ext + "$"),
59+
re_d: new RegExp("\\.d\\" + ext + "$"),
60+
re_except_d: new RegExp("^(?!.*\\.d\\" + ext + "$).*\\" + ext + "$"),
61+
re_index: new RegExp("(?:^|[\\\\\\/])index\\" + ext + "$")
5862
};
5963
}
6064

6165
const defaultExtension = setupExtension(".ts");
6266

6367
// Proxy Binaryen's ready event
6468
Object.defineProperty(exports, "ready", {
65-
get: function() { return binaryen.ready; }
69+
get() { return binaryen.ready; }
6670
});
6771

6872
// Emscripten adds an `uncaughtException` listener to Binaryen that results in an additional
@@ -76,24 +80,21 @@ var isDev = false;
7680
try {
7781
assemblyscript = require("assemblyscript");
7882
} catch (e) {
79-
function dynRequire(...args) {
80-
return eval("require")(...args);
81-
}
8283
try { // `asc` on the command line
83-
assemblyscript = dynRequire("../dist/assemblyscript.js");
84+
assemblyscript = dynrequire("../dist/assemblyscript.js");
8485
} catch (e) {
8586
try { // `asc` on the command line without dist files
86-
dynRequire("ts-node").register({
87+
dynrequire("ts-node").register({
8788
project: path.join(__dirname, "..", "src", "tsconfig.json"),
8889
skipIgnore: true,
8990
compilerOptions: { target: "ES2016" }
9091
});
91-
dynRequire("../src/glue/js");
92-
assemblyscript = dynRequire("../src");
92+
dynrequire("../src/glue/js");
93+
assemblyscript = dynrequire("../src");
9394
isDev = true;
9495
} catch (e_ts) {
9596
try { // `require("dist/asc.js")` in explicit browser tests
96-
assemblyscript = dynRequire("./assemblyscript");
97+
assemblyscript = dynrequire("./assemblyscript");
9798
} catch (e) {
9899
throw Error(e_ts.stack + "\n---\n" + e.stack);
99100
}
@@ -109,7 +110,7 @@ exports.isBundle = typeof BUNDLE_VERSION === "string";
109110
exports.isDev = isDev;
110111

111112
/** AssemblyScript version. */
112-
exports.version = exports.isBundle ? BUNDLE_VERSION : require("../package.json").version;
113+
exports.version = exports.isBundle ? BUNDLE_VERSION : dynrequire("../package.json").version;
113114

114115
/** Available CLI options. */
115116
exports.options = require("./asc.json");
@@ -129,16 +130,21 @@ exports.libraryFiles = exports.isBundle ? BUNDLE_LIBRARY : (() => { // set up if
129130
const bundled = {};
130131
find
131132
.files(libDir, defaultExtension.re_except_d)
132-
.forEach(file => bundled[file.replace(defaultExtension.re, "")] = fs.readFileSync(path.join(libDir, file), "utf8" ));
133+
.forEach(file => {
134+
bundled[file.replace(defaultExtension.re, "")] = fs.readFileSync(path.join(libDir, file), "utf8");
135+
});
133136
return bundled;
134137
})();
135138

136139
/** Bundled definition files. */
137140
exports.definitionFiles = exports.isBundle ? BUNDLE_DEFINITIONS : (() => { // set up if not a bundle
138-
const stdDir = path.join(__dirname, "..", "std");
141+
const readDefinition = name => fs.readFileSync(
142+
path.join(__dirname, "..", "std", name, "index" + defaultExtension.ext_d),
143+
"utf8"
144+
);
139145
return {
140-
"assembly": fs.readFileSync(path.join(stdDir, "assembly", "index" + defaultExtension.ext_d), "utf8"),
141-
"portable": fs.readFileSync(path.join(stdDir, "portable", "index" + defaultExtension.ext_d), "utf8")
146+
assembly: readDefinition("assembly"),
147+
portable: readDefinition("portable")
142148
};
143149
})();
144150

@@ -159,15 +165,17 @@ exports.compileString = (sources, options) => {
159165
if (opt && opt.type === "b") {
160166
if (val) argv.push("--" + key);
161167
} else {
162-
if (Array.isArray(val)) val.forEach(val => argv.push("--" + key, String(val)));
168+
if (Array.isArray(val)) {
169+
val.forEach(val => { argv.push("--" + key, String(val)); });
170+
}
163171
else argv.push("--" + key, String(val));
164172
}
165173
});
166174
exports.main(argv.concat(Object.keys(sources)), {
167175
stdout: output.stdout,
168176
stderr: output.stderr,
169177
readFile: name => Object.prototype.hasOwnProperty.call(sources, name) ? sources[name] : null,
170-
writeFile: (name, contents) => output[name] = contents,
178+
writeFile: (name, contents) => { output[name] = contents; },
171179
listFiles: () => []
172180
});
173181
return output;
@@ -417,11 +425,11 @@ exports.main = function main(argv, options, callback) {
417425
for (let i = 0, k = transformArgs.length; i < k; ++i) {
418426
let filename = transformArgs[i].trim();
419427
if (!tsNodeRegistered && filename.endsWith(".ts")) { // ts-node requires .ts specifically
420-
require("ts-node").register({ transpileOnly: true, skipProject: true, compilerOptions: { target: "ES2016" } });
428+
dynrequire("ts-node").register({ transpileOnly: true, skipProject: true, compilerOptions: { target: "ES2016" } });
421429
tsNodeRegistered = true;
422430
}
423431
try {
424-
const classOrModule = require(require.resolve(filename, { paths: [baseDir, process.cwd()] }));
432+
const classOrModule = dynrequire(dynrequire.resolve(filename, { paths: [baseDir, process.cwd()] }));
425433
if (typeof classOrModule === "function") {
426434
Object.assign(classOrModule.prototype, {
427435
program,
@@ -953,11 +961,10 @@ exports.main = function main(argv, options, callback) {
953961
filename = path.basename(filename);
954962
const outputFilePath = path.join(dirPath, filename);
955963
if (!fs.existsSync(dirPath)) mkdirp(dirPath);
956-
if (typeof contents === "string") {
957-
fs.writeFileSync(outputFilePath, contents, { encoding: "utf8" } );
958-
} else {
959-
fs.writeFileSync(outputFilePath, contents);
960-
}
964+
fs.writeFileSync(
965+
outputFilePath, contents,
966+
typeof contents === "string" ? { encoding: "utf8" } : void 0
967+
);
961968
});
962969
return true;
963970
} catch (e) {
@@ -970,7 +977,8 @@ exports.main = function main(argv, options, callback) {
970977
try {
971978
stats.readCount++;
972979
stats.readTime += measure(() => {
973-
files = fs.readdirSync(path.join(baseDir, dirname)).filter(file => extension.re_except_d.test(file));
980+
files = fs.readdirSync(path.join(baseDir, dirname))
981+
.filter(file => extension.re_except_d.test(file));
974982
});
975983
return files;
976984
} catch (e) {
@@ -1111,9 +1119,7 @@ exports.formatTime = formatTime;
11111119

11121120
/** Formats and prints out the contents of a set of stats. */
11131121
function printStats(stats, output) {
1114-
function format(time, count) {
1115-
return pad(formatTime(time), 12) + " n=" + count;
1116-
}
1122+
const format = (time, count) => pad(formatTime(time), 12) + " n=" + count;
11171123
(output || process.stdout).write([
11181124
"I/O Read : " + format(stats.readTime, stats.readCount),
11191125
"I/O Write : " + format(stats.writeTime, stats.writeCount),
@@ -1130,8 +1136,8 @@ function printStats(stats, output) {
11301136
exports.printStats = printStats;
11311137

11321138
var allocBuffer = typeof global !== "undefined" && global.Buffer
1133-
? global.Buffer.allocUnsafe || function(len) { return new global.Buffer(len); }
1134-
: function(len) { return new Uint8Array(len); };
1139+
? global.Buffer.allocUnsafe || (len => new global.Buffer(len))
1140+
: len => new Uint8Array(len);
11351141

11361142
/** Creates a memory stream that can be used in place of stdout/stderr. */
11371143
function createMemoryStream(fn) {

cli/util/options.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -237,11 +237,15 @@ function merge(config, currentOptions, parentOptions, parentBaseDir) {
237237

238238
exports.merge = merge;
239239

240+
const dynrequire = typeof __webpack_require__ === "function"
241+
? __non_webpack_require__
242+
: require;
243+
240244
/** Resolves a single possibly relative path. Keeps absolute paths, otherwise prepends baseDir. */
241245
function resolvePath(p, baseDir, useNodeResolution = false) {
242246
if (path.isAbsolute(p)) return p;
243247
if (useNodeResolution && !p.startsWith(".")) {
244-
return require.resolve(p, { paths: [ baseDir ] });
248+
return dynrequire.resolve(p, { paths: [ baseDir ] });
245249
}
246250
return path.join(baseDir, p);
247251
}

webpack.config.js

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,7 @@ const bin = {
6666
entry: [ "./asc.js" ],
6767
externals: [
6868
"binaryen",
69-
"assemblyscript",
70-
"ts-node"
69+
"assemblyscript"
7170
],
7271
node: {
7372
"buffer": false,
@@ -106,9 +105,6 @@ const bin = {
106105
__dirname: JSON.stringify(".")
107106
}),
108107

109-
// Ignored node-only dependencies
110-
new webpack.IgnorePlugin(/\.\/src|package\.json|^(ts-node|glob)$/),
111-
112108
// Browser shims
113109
new webpack.NormalModuleReplacementPlugin(/^path$/, path.join(shimDir, "path")),
114110
new webpack.NormalModuleReplacementPlugin(/^process$/, path.join(shimDir, "process")),

0 commit comments

Comments
 (0)