UNPKG

11.5 kBJavaScriptView Raw
1var ts = require('gulp-typescript');
2var compile = require('./gulp-compile');
3var oldCompile = require('./gulp-old-compile');
4var amdToNetSuite = require('./gulp-amd-to-netsuite');
5var path = require('path');
6var fs = require('fs-extra');
7var cp = require('child_process');
8var https = require('https');
9var os = require('os');
10var webpack = require('webpack');
11var walk = require('fs-walk');
12var deepmerge = require('deepmerge');
13var WrapperPlugin = require('wrapper-webpack-plugin');
14
15function getCLIOpenCommand() {
16 switch (os.platform()) {
17 case 'darwin' :
18 return 'open'; // Mac OS X
19 case 'win32' :
20 return 'start notepad'; // Windows - Use Notepad since the file doesn't technically have a registered extension
21 default :
22 return 'xdg-open'; // Linux/Sunos/UNIX
23 }
24}
25
26function setupNSCredentialsFile() {
27 var credFilePath = path.join(os.homedir(), '.netsuite-credentials');
28 var credentialsTemplateString =
29 ['{',
30 ' "accountnumber": {',
31 ' "email": "youremail@yourcompany.com",',
32 ' "role": "18",',
33 ' "password": "password"',
34 ' }',
35 '}'].join('\n');
36 fs.stat(credFilePath, function (err) {
37 if (!err) {
38 console.log('.netsuite-credentials file already exists. Opening file using default application...');
39 cp.exec(getCLIOpenCommand() + ' ' + credFilePath);
40 } else if (err.code === 'ENOENT') {
41 fs.writeFile(credFilePath, credentialsTemplateString);
42 console.log('.netsuite-credentials file created. Opening file using default application...');
43 cp.exec(getCLIOpenCommand() + ' ' + credFilePath);
44 } else {
45 console.log("Something went wrong. =( Error details: " + err.code);
46 }
47 });
48}
49
50
51function getFileArguments() {
52 var nextIsFile = false;
53 var filePaths = [];
54 for (var i = 0; i < process.argv.length; i++) {
55 var arg = process.argv[i];
56 if (nextIsFile) {
57 var filePath = path.resolve(path.relative('', arg));
58 filePaths.push(filePath);
59 nextIsFile = false;
60 } else if (arg.toLowerCase() === '--file') {
61 nextIsFile = true;
62 }
63 }
64 return filePaths;
65}
66
67function generateVinylPaths(basePath, extension, exclusions) {
68 var excludedDirectories = ['library', 'lib', 'fragments', 'frags', 'vendor', 'externs', 'Fragments', 'Frags'];
69 var fileArguments = getFileArguments();
70 var paths = [];
71 if (fileArguments.length > 0) {
72 for (var i = 0; i < fileArguments.length; i++) {
73 var relPath = path.relative(basePath, fileArguments[i]);
74 if (relPath.split(path.sep).indexOf('..') === -1) {
75 if (path.extname(fileArguments[i]) === '.' + extension) {
76 paths.push(fileArguments[i]);
77 }
78 }
79 }
80 } else {
81 paths = [basePath + '/**/*.' + extension];
82 }
83 if (paths.length === 0) return [];
84 //Construct the final array of vinyl paths
85 paths = paths.concat(
86 excludedDirectories.map(
87 function (exclude) {
88 return '!' + basePath + '/**/*' + exclude + '*/**/*.' + extension;
89 }
90 )
91 ).concat(exclusions.map(
92 function (exclusion) {
93 return '!' + exclusion;
94 }
95 ));
96 return paths;
97}
98
99var paths = {
100 out: './build',
101 package: './package.json'
102};
103
104function doClean(callback) {
105 fs.remove(paths.out, callback);
106}
107
108exports.setupHITCGulp = function (gulp, context, config) {
109 var exclusions = [];
110 if (config && config.length > 0) {
111 config.forEach(function (configObj) {
112 if (configObj['paths']) {
113 exclusions = exclusions.concat(configObj['paths']);
114 }
115 });
116 }
117
118 gulp.task('clean', function (callback) {
119 doClean(callback);
120 });
121
122 gulp.task('setup-ns-credentials-file', function () {
123 setupNSCredentialsFile()
124 });
125
126 /* SSv1 */
127 gulp.task('build-ssv1-browserify', function () {
128 var p = './ssv1/browserify';
129 var srcPaths = generateVinylPaths(p, 'js', exclusions)
130 .concat(generateVinylPaths(p, 'coffee', exclusions));
131 return gulp.src(srcPaths, {base: p})
132 .pipe(compile())
133 .pipe(gulp.dest(path.join(paths.out, p)));
134 });
135
136 gulp.task('build-ssv1-old-compiler', function () {
137 var p = './ssv1/old-compiler';
138 var srcPaths = generateVinylPaths(p, 'js', exclusions);
139 return gulp.src(srcPaths, {base: p})
140 .pipe(oldCompile())
141 .pipe(gulp.dest(path.join(paths.out, p)));
142 });
143
144 gulp.task('build-ssv1', ['build-ssv1-browserify', 'build-ssv1-old-compiler']);
145
146 /* SSv2 */
147 gulp.task('build-ssv2-typescripts', function () {
148 var p = 'ssv2';
149 var tsProject = ts.createProject('tsconfig.json');
150 return gulp.src(generateVinylPaths(p, 'ts', exclusions).concat(generateVinylPaths(p, 'tsx', exclusions)), {base: p})
151 .pipe(tsProject())
152 .js.pipe(amdToNetSuite())
153 .pipe(gulp.dest(path.join(paths.out, p)));
154 });
155
156 gulp.task('build-ssv2-.d.ts', function () {
157 var p = 'ssv2';
158 var tsProject = ts.createProject('tsconfig.json', {declaration: true, allowJs: false});
159 return gulp.src(generateVinylPaths(p, 'ts', exclusions).concat('typings/index.d.ts'), {base: p})
160 .pipe(tsProject())
161 .dts.pipe(gulp.dest(path.join(paths.out, p)));
162 });
163
164 gulp.task('build-ssv2-javascripts', function () {
165 var p = 'ssv2';
166 return gulp.src(generateVinylPaths(p, 'js', exclusions), {base: p})
167 .pipe(gulp.dest(path.join(paths.out, p)));
168 });
169
170 gulp.task('build-ssv2-webpack', function (callback) {
171 if (!config) return callback();
172
173 const webpackConfigs = config.filter(function (configObj) {
174 return configObj['compileMethod'] === 'webpack';
175 });
176 if (!webpackConfigs || webpackConfigs.length === 0) return callback();
177
178 const externals = {};
179 fs.readdirSync(path.resolve(context, "node_modules/@hitc/netsuite-types/N")).forEach(function (file) {
180 if (file === '.' || file === '..') return;
181 const module = 'N/' + file.replace('.d.ts', '');
182 externals[module] = {amd: module};
183 });
184
185 const ssv2UtilitiesPath = path.resolve(context, "node_modules/@hitc/ssv2-utilities");
186 walk.filesSync(ssv2UtilitiesPath, function (basedir, filename) {
187 const moduleComponent = path.relative(ssv2UtilitiesPath, path.resolve(basedir, filename.replace(/(\.d)?\.(j|t)sx?$/, '')));
188 const module = '/.bundle/121445/HITCSSV2Utilities/' + moduleComponent;
189 externals[module] = {amd: module};
190 });
191
192 const ssv2VendorConfigPath = path.resolve(context, "node_modules/@hitc/ssv2-utilities/vendor/webpack.config.js");
193 if (fs.existsSync(ssv2VendorConfigPath)) {
194 const vendorConfig = require(ssv2VendorConfigPath);
195 Object.keys(vendorConfig.entry).forEach(function (vendorModule) {
196 externals[vendorModule] = {amd: '/.bundle/121445/HITCSSV2Utilities/vendor/' + vendorModule};
197 });
198 }
199
200 const defaultWebpackConfig = {
201 context: context,
202 output: {
203 libraryTarget: 'amd'
204 },
205 resolve: {
206 extensions: ['.ts', '.tsx', '.js', '.jsx']
207 },
208 devtool: 'eval-source-map',
209 module: {
210 rules: [
211 {
212 test: /\.tsx?$/,
213 loader: 'ts-loader'
214 },
215 {
216 test: /\.css$/,
217 loaders: ['style-loader', 'css-loader']
218 }
219 ]
220 },
221 externals,
222 plugins: [
223 new WrapperPlugin({
224 header: "/**\n * @NAPIVersion 2.0\n * @NModuleScope Public\n */\n"
225 }),
226 ]
227 };
228
229 var count = 0;
230 var anyFilesBeingProcessed = false;
231 webpackConfigs.forEach(function (configObj) {
232 configObj.paths.forEach(function (thisPath) {
233 const fileArguments = getFileArguments();
234 if (fileArguments.length > 0) {
235 if (!~fileArguments.indexOf(path.resolve(path.relative('', thisPath)))) return;
236 }
237 const pathConfig = {
238 entry: ['./' + path.relative(context, thisPath)],
239 output: {
240 filename: path.basename(thisPath, path.extname(thisPath)) + '.js',
241 path: path.resolve(paths.out, path.dirname(path.relative(context, thisPath)))
242 }
243 };
244 const webpackConfig = deepmerge.all([
245 defaultWebpackConfig,
246 configObj['webpackConfig'] || {},
247 pathConfig,
248 ]);
249 if (configObj['devLibraries']) {
250 configObj['devLibraries'].forEach(function (devLibrary) {
251 delete webpackConfig.externals[devLibrary];
252 });
253 }
254 count++;
255 anyFilesBeingProcessed = true;
256 webpack(webpackConfig, function (err) {
257 if (err) console.error(err);
258 if (--count === 0) callback();
259 });
260 });
261 });
262 if (!anyFilesBeingProcessed) return callback();
263 });
264
265 gulp.task('build-ssv2', ['build-ssv2-typescripts', 'build-ssv2-javascripts', 'build-ssv2-webpack']);
266
267 gulp.task('build', ['build-ssv1', 'build-ssv2']);
268
269 var extensionsToReplace = {
270 ".ts": ".js",
271 ".tsx": '.js',
272 ".coffee": ".js"
273 };
274
275 function doUpload(environment, cb) {
276 var netsuiteUploadPath = path.resolve(path.dirname(paths.package), "node_modules", "@hitc", "netsuite-upload", "release", "app.js");
277 var pathsToUpload = [];
278 var fileArguments = getFileArguments();
279 for (var i = 0; i < fileArguments.length; i++) {
280 var arg = fileArguments[i];
281 var uploadPath = path.resolve(paths.out, path.relative('', arg));
282 for (var ext in extensionsToReplace) {
283 var thisExt = path.extname(uploadPath);
284 if (thisExt === ext) {
285 uploadPath = uploadPath.replace(thisExt, extensionsToReplace[ext]);
286 }
287 }
288 pathsToUpload.push(uploadPath);
289 }
290 if (!pathsToUpload.length) {
291 pathsToUpload.push(paths.out);
292 }
293 var command = [
294 "node",
295 "\"" + netsuiteUploadPath + "\"",
296 "-p",
297 "\"" + paths.package + "\"",
298 "-e",
299 "\"" + environment + "\"",
300 "-b",
301 "\"" + paths.out + "\""
302 ];
303 for (i = 0; i < pathsToUpload.length; i++) {
304 command.push("\"" + pathsToUpload[i] + "\"");
305 }
306 cp.exec(
307 command.join(' '),
308 function (err, stdout, stderr) {
309 console.log(stdout);
310 console.log(stderr);
311 cb(err);
312 }
313 );
314 }
315
316 gulp.task('upload', function (cb) {
317 doUpload('PRODUCTION', cb);
318 });
319
320 gulp.task('upload-sandbox', function (cb) {
321 doUpload('SANDBOX', cb);
322 });
323
324 gulp.task('upload-beta', function (cb) {
325 doUpload('BETA', cb);
326 });
327
328 gulp.task('build-and-upload', ['build'], function (cb) {
329 doUpload('PRODUCTION', cb)
330 });
331
332 gulp.task('build-and-upload-sandbox', ['build'], function (cb) {
333 doUpload('SANDBOX', cb)
334 });
335
336 gulp.task('build-and-upload-beta', ['build'], function (cb) {
337 doUpload('BETA', cb)
338 });
339
340 gulp.task('watch', ['build'], function () {
341 gulp.watch(paths.scripts, ['build']);
342 });
343
344 gulp.task('install-ssv2-utilities', function (cb) {
345 var data = "";
346 https.get("https://raw.githubusercontent.com/headintheclouddev/ssv2-utilities/master/ssv2-utilities.d.ts", function (res) {
347 res.on('data', function (chunk) {
348 data += chunk;
349 });
350 res.on('end', function () {
351 fs.writeFileSync('./typings/ssv2-utilities.d.ts', data);
352 var indexContent = "" + fs.readFileSync('./typings/index.d.ts');
353 if (indexContent.search('ssv2-utilities.d.ts') === -1) {
354 indexContent += "\n/// <reference path=\"ssv2-utilities.d.ts\" />";
355 fs.writeFileSync('./typings/index.d.ts', indexContent);
356 }
357 cb();
358 });
359 }).on('error', function (e) {
360 console.error(e);
361 cb();
362 });
363 });
364};