-
Notifications
You must be signed in to change notification settings - Fork 21
/
plugin.js
113 lines (101 loc) · 2.92 KB
/
plugin.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
/* Babel 7 transform */
var babylon = require("babylon");
var generate = require("@babel/generator").default;
function printNode(ast) {
return generate(ast, {}).code;
}
function parse(code) {
return babylon.parse(code, {
allowImportExportEverywhere: true,
allowReturnOutsideFunction: true,
allowSuperOutsideMethod: true,
}).program;
}
var transform = require("nodent-transform").transform;
function transformAsyncToPromises(api, options) {
var requiresTranspilation;
var runtime = options.runtime ? (typeof options.runtime==="string" ? options.runtime : "$nodent_runtime") : null;
var opts = {
// Code generation options
es6target: false,
babelTree: true,
engine: false,
generators: false,
promises: true,
lazyThenables: false,
wrapAwait: true,
noRuntime: !runtime,
$runtime: runtime,
generatedSymbolPrefix: "$",
$return: "$return",
$error: "$error",
$arguments: "$args",
$Promise: "Promise",
$asyncspawn: "$asyncspawn",
$asyncbind: "$asyncbind",
$makeThenable: "$makeThenable",
};
if (options.codeGenerationOptions) {
var keys = Object.keys(options.codeGenerationOptions);
for (var i = 0; i < keys.length; i++) {
if (keys[i] in opts) {
opts[keys[i]] = options.codeGenerationOptions[keys[i]];
}
}
}
return {
visitor: {
Program: {
enter: function() {
requiresTranspilation = false;
},
exit: function(path, state) {
// Check if there was an async or await keyword before bothering to process the AST
if (!requiresTranspilation) return;
var newAst = transform(
{
// Input: the ast and filename
filename: state.filename,
ast: path.node,
},
opts,
{
// Helpers for the transformer:
parse: parse, // Parse a JS fragment into an AST
printNode: printNode, // Print a node as JS source
logger: false /* console.log.bind(console)*/, // Log a warning
}
).ast;
if (runtime) {
newAst.body.splice(0, 0, {
type: "ImportDeclaration",
specifiers: [
{
type: "ImportDefaultSpecifier",
local: {
type: "Identifier",
name: runtime,
},
},
],
importKind: "value",
source: {
type: "StringLiteral",
value: "nodent-runtime/promise",
},
});
}
},
},
AwaitExpression: function Function() {
requiresTranspilation = true;
},
Function: function Function(path) {
if (path.node.async) {
requiresTranspilation = true;
}
},
},
};
}
module.exports = transformAsyncToPromises;