UNPKG

1.22 kBJavaScriptView Raw
1/**
2 * Copyright (c) 2014-present, Facebook, Inc.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8var recast = require("recast");
9var types = recast.types;
10var n = types.namedTypes;
11var util = require("./util.js");
12
13exports.transform = function transform(node, options) {
14 options = util.defaults(options || {}, {
15 includeRuntime: false
16 });
17
18 var result = require("@babel/core").transformFromAstSync(node, null, {
19 presets: [require("regenerator-preset")],
20 code: false,
21 ast: true
22 });
23
24 node = result.ast;
25
26 if (options.includeRuntime === true) {
27 injectRuntime(n.File.check(node) ? node.program : node);
28 }
29
30 return node;
31};
32
33function injectRuntime(program) {
34 n.Program.assert(program);
35
36 // Include the runtime by modifying the AST rather than by concatenating
37 // strings. This technique will allow for more accurate source mapping.
38 var runtimePath = require("..").runtime.path;
39 var runtime = fs.readFileSync(runtimePath, "utf8");
40 var runtimeBody = recast.parse(runtime, {
41 sourceFileName: runtimePath
42 }).program.body;
43
44 var body = program.body;
45 body.unshift.apply(body, runtimeBody);
46}