-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
218 lines (174 loc) · 5.37 KB
/
index.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
const os = require('os');
const fs = require('fs-extra');
const path = require('path');
const crypto = require('crypto');
const { execSync } = require('child_process');
const paths = require('env-paths')('nodejs-inline-cpp', {suffix: ''});
const findParentDir = require('find-parent-dir');
const debug = require('debug')('inline-cpp');
const _ = require('lodash');
let nodeAddon, nodeGyp;
function findBuildDeps() {
if (nodeAddon && nodeGyp) return;
nodeAddon = require.resolve('node-addon-api');
nodeAddon = findParentDir.sync(nodeAddon, 'package.json');
nodeGyp = require.resolve('node-gyp');
nodeGyp = findParentDir.sync(nodeGyp, 'package.json');
nodeGyp = path.join(nodeGyp, 'bin', 'node-gyp.js');
debug('Using node-gyp:', nodeGyp);
debug('Using node-addon-api:', nodeAddon);
// For some reason, windows needs path to be escaped
if (os.platform() === 'win32') {
nodeAddon = nodeAddon.replace(/[\\$'"]/g, "\\$&")
}
}
function optsMerge(objValue, srcValue) {
if (_.isArray(objValue)) {
return objValue.concat(srcValue);
}
}
function generateModule(code, opts) {
opts = opts || {};
code = code.trim();
// The stripped code is only used for some auto-detection, it is not actually compiled!
const strippedCode = ' ' + code
.replace(/,/g, ' , ')
.replace(/\(/g, ' ( ')
.replace(/\)/g, ' ) ')
.replace(/{/g, ' { ')
.replace(/}/g, ' } ')
.replace(/\s\s+/g, ' ') + ' ';
// Find all function declarations
let funcsRe = /(([a-zA-Z_][\w:]*)\s+([a-zA-Z_]\w*)\s*\(\s*((?:[a-zA-Z0-9_:&\*,\s])*)\s*\))\s*{/gm;
let m;
let funcs = [];
let funcSingle, funcInit;
while ((m = funcsRe.exec(strippedCode)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === funcsRe.lastIndex) {
funcsRe.lastIndex++;
}
const func = {
signature: m[1],
name: m[3],
returns: m[2],
arguments: m[4]
}
debug('Function:', func.signature);
if (func.name === 'Init') {
funcInit = func;
} else {
funcs.push(func);
}
}
if (funcs.length === 1) funcSingle = funcs[0];
let init = '';
// If init function is not provided, generate it
if (!funcInit) {
init = 'Object Init(Env env, Object exports) {\n';
for (let f of funcs) {
init += ` exports.Set("${f.name}", Function::New(env, ${f.name}));\n`;
}
init += ' return exports;\n'
init += '}\n';
}
let body =
`
#include <napi.h>
using namespace Napi;
${code}
${init}
NODE_API_MODULE(addon, Init)
`;
// Generate a hash using actual code and build options
const modName = 'm_' + crypto.createHash('sha1').update(JSON.stringify(opts)).update(body).digest("hex");
const modPath = path.join(paths.cache, modName);
const modNode = path.join(modPath, modName+'.node');
// If the same hash exists, try loading it
if (fs.existsSync(modNode)) {
debug('Loading cached', modPath);
try {
if (funcSingle && !funcInit) {
return require(modNode)[funcSingle.name];
} else {
return require(modNode);
}
} catch(e) {}
}
// Ok no luck, let's build it...
findBuildDeps();
let gypTarget = {
"target_name": modName,
"sources": [
"module.cpp"
],
"include_dirs": [
`<!@(node -p "require('${nodeAddon}').include")`
],
"dependencies": [
`<!(node -p "require('${nodeAddon}').gyp")`
],
"cflags!": ["-fno-exceptions"],
"cflags_cc!": ["-fno-exceptions"],
"xcode_settings": {
"GCC_ENABLE_CPP_EXCEPTIONS": "YES",
"CLANG_CXX_LIBRARY": "libc++",
"MACOSX_DEPLOYMENT_TARGET": "10.7",
},
"msvs_settings": {
"VCCLCompilerTool": { "ExceptionHandling": 1 },
},
"defines": ["NAPI_CPP_EXCEPTIONS"],
}
gypTarget = _.mergeWith(gypTarget, opts, optsMerge)
let binding = {
"targets": [ gypTarget ]
};
debug('Building', modPath);
fs.ensureDirSync(modPath);
fs.writeFileSync(path.join(modPath, 'module.cpp'), body);
fs.writeJsonSync(path.join(modPath, 'binding.gyp'), binding, { spaces: 2 });
let execOpts = {
stdio: (debug.enabled) ? [0,1,2] : [null,null,null]
};
execSync(`node "${nodeGyp}" configure --directory="${modPath}"`, execOpts)
try {
execSync(`node "${nodeGyp}" build --directory="${modPath}"`, execOpts)
fs.renameSync(path.join(modPath, 'build', 'Release', modName+'.node'), modNode)
fs.removeSync(path.join(modPath, 'build'))
if (funcSingle && !funcInit) {
return require(modNode)[funcSingle.name];
} else {
return require(modNode);
}
} catch (e) {
throw new Error('C++ build failed')
}
}
function compiler(opts) {
return function(obj) {
let compileString;
// Handle tagged template invocation
if (Array.isArray(obj) && Array.isArray(obj.raw)) {
let interpVals = [].concat(Array.prototype.slice.call(arguments)).slice(1);
compileString = obj[0];
for (let i = 0, l = interpVals.length; i < l; i++) {
compileString += '' + interpVals[i] + obj[i + 1];
}
} else if (typeof obj === 'string' || obj instanceof String) {
compileString = obj;
}
if (compileString) {
return generateModule(compileString, opts);
}
throw new Error('Wrong arguments for inline-cpp')
}
}
module.exports = function(obj) {
if (typeof obj === 'object' &&
!Array.isArray(obj)
) {
return compiler(obj)
}
return compiler()(obj)
}