forked from nm90/strike-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
executable file
·598 lines (517 loc) · 16.5 KB
/
app.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
#!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var http = require('https');
var prompt = require('prompt');
var jsforce = require('jsforce');
var chalk = require('chalk');
var figlet = require('figlet');
var clear = require('clear');
var low = require('lowdb');
var async = require('async');
var commander = require('commander');
var tokenParser = require('./tokenParser.js');
var rimraf = require('rimraf');
const REPO_BASE_URL = 'https://raw.githubusercontent.com/appiphony/Strike-Components/master';
const SANDBOX_URL = 'https://test.salesforce.com';
const DEVELOPER_EDITION_URL = 'https://login.salesforce.com';
const fileExtensionMap = {
COMPONENT: '.cmp',
CONTROLLER: 'Controller.js',
HELPER: 'Helper.js',
RENDERER: 'Renderer.js',
EVENT: '.evt',
RESOURCE: '.resource',
STYLE: '.css',
TOKENS: '.tokens'
};
const fileFormatMap = {
COMPONENT: 'XML',
CONTROLLER: 'JS',
HELPER: 'JS',
RENDERER: 'JS',
EVENT: 'XML',
TOKENS: 'XML',
STYLE: 'CSS'
};
var db;
var dependencyMap;
var conn = new jsforce.Connection({
loginUrl: getLoginUrl()
});
if(doesCommandExist('disconnect')){
fs.unlinkSync(process.cwd() + '/db.json');
console.log('Credentials have been disconnected');
} else if(doesCommandExist('connect')){
initializeDatabase();
prompt.start();
getUserInput(function(callback, userInput){
saveUserInput(userInput.username, userInput.password);
console.log('Credentials for ' + userInput.username + ' connected');
});
} else if(upsertCommandExists()){
initializeDatabase();
drawScreen();
createStrikeComponentFolder();
prompt.start();
async.waterfall([
downloadDependencyMap,
downloadTargetComponents,
getUserInput,
login,
upsertComponentFiles,
], function(err){
if (err) { console.error(chalk.red(err)); }
rimraf(process.cwd() + '/strike-components', function (err) {
if (err) { return console.error(chalk.red(err)); }
});
});
} else{
downloadDependencyMap(function(){
configureHelpCommand();
console.log(process.argv[2] + ' is not a valid command');
commander.outputHelp();
});
}
function getLoginUrl(){
return sandboxFlagExists() ? SANDBOX_URL : DEVELOPER_EDITION_URL;
}
function getUserInput(callback){
prompt.get(configurePromptSchema(), function (err, res){
if (err) { return console.error(chalk.red(err)); }
var userInput = createUserInputObj(res);
callback(null, userInput);
});
}
function login(userInput, callback){
conn.login(userInput.username, userInput.password, function(err) {
if (err) {
callback(err);
} else{
callback(null);
}
});
}
function upsertComponentFiles(callback){
var bundlesToCreate = dependencyMap[process.argv[3]];
async.eachSeries(bundlesToCreate, function(bundle, callback){
if(isApex(bundle)){
//we are not creating a bundle, we need to create an apex class instead
createApexClass(bundle, function(){
callback(null);
});
} else {
var tmpBundleInfo = {
name: bundle,
description: 'I was created from Strike-CLI'
};
if(requiresD3(bundle)){
createStaticResource('d3');
}
createAuraDefinitionBundle(tmpBundleInfo, function(){
callback(null);
});
}
}, function(err){
if(err) {
callback(null, err);
} else {
callback(null, 'done');
}
});
}
function requiresD3(bundle){
return bundle === 'strike_chart';
}
function doesCommandExist(command){
return process.argv[2] === command;
}
function upsertCommandExists(){
return process.argv[2] == 'install' || process.argv[2] == 'update' || process.argv[2] == 'upsert';
}
function initializeDatabase(){
db = low('db.json');
db.defaults({ credentials: []})
.value();
}
function drawScreen(){
clear();
console.log(
chalk.cyan(
figlet.textSync('Strike-CLI', { horizontalLayout: 'full' })
)
);
}
function createStrikeComponentFolder(){
rimraf(process.cwd() + '/strike-components', function (err) {
if (err) { return console.error(chalk.red(err)); }
fs.existsSync(process.cwd() + '/strike-components') || fs.mkdirSync(process.cwd() + '/strike-components');
});
}
function downloadDependencyMap(callback){
http.get(REPO_BASE_URL + '/dependency.json', function(response){
if (response.statusCode !== 200) {
return console.error(chalk.red(response));
}
var body = '';
response.on('data', function(d){
body += d;
});
response.on('end', function(){
dependencyMap = JSON.parse(body);
callback();
});
});
}
function downloadTargetComponents(callback){
if(dependencyMap.hasOwnProperty(process.argv[3])){
var targetComponents = dependencyMap[process.argv[3]];
targetComponents.forEach(function(componentName){
downloadComponentBundle(componentName);
});
callback(null);
} else {
callback(new Error('Sorry, ' + process.argv[3] + ' is not a supported component'));
}
}
function isApex(fileName){
return fileName.substring(fileName.length - 4) === '.cls';
}
function downloadComponentBundle(componentName){
if(isApex(componentName)){
downloadFile(componentName, 'APEX');
} else {
fs.mkdirSync(process.cwd() + '/strike-components/' + componentName);
if(requiresD3(componentName)){
downloadFile('d3', 'RESOURCE');
}
var fileTypes = ['COMPONENT', 'CONTROLLER', 'HELPER', 'RENDERER', 'EVENT', 'STYLE', 'TOKENS'];
fileTypes.forEach(function(fileType){
downloadFile(componentName, fileType);
});
}
}
function downloadFile(fileName, fileExtension){
var fileSource;
var fileDestination;
var defaultPermissions = 0o755;
if(fileExtension === 'RESOURCE'){
fileSource = REPO_BASE_URL + '/staticresources/' + fileName + fileExtensionMap[fileExtension];
fileDestination = fs.createWriteStream(process.cwd() + '/strike-components/' + fileName + fileExtensionMap[fileExtension], {flags: 'w', mode: defaultPermissions});
} else if(fileExtension === 'APEX'){
fileSource = REPO_BASE_URL + '/classes/' + fileName;
fileDestination = fs.createWriteStream(process.cwd() + '/strike-components/' + fileName, {flags: 'w', mode: defaultPermissions});
} else {
fileSource = REPO_BASE_URL + '/aura/' + fileName + '/' + fileName + fileExtensionMap[fileExtension];
fileDestination = fs.createWriteStream(process.cwd() + '/strike-components/' + fileName + '/' + fileName + fileExtensionMap[fileExtension], {flags: 'w', mode: defaultPermissions});
}
async.waterfall([
function requestFile(callback){
http.get(fileSource, function(response) {
callback(null, response);
});
},
function writeResponseToFile(response, callback){
response.pipe(fileDestination);
var body = '';
response.on('data', function(d){
body += d;
});
response.on('end', function(){
callback(null, body);
});
}
], function(err){
if (err) { return console.error(chalk.red(err)); }
});
}
function validContent(body){
return body != '404: Not Found\n';
}
function configurePromptSchema(){
if(!credentialsExist()){
prompt.message = 'Strike-CLI';
var promptSchema = {
properties: {
username: {
description: 'Username'
},
password: {
description: 'Password',
hidden: true
}
}
};
return promptSchema;
} else {
return {properties:{}}; //will not prompt user for any questions
}
}
function credentialsExist(){
return db.get('credentials').find({ id: 1 }).value() != undefined;
}
function createUserInputObj(promptResponse){
var userInputObj = {
username: promptResponse.username || db.get('credentials').find({ id: 1 }).value().username,
password: promptResponse.password || db.get('credentials').find({ id: 1 }).value().password,
bundleInfo: {
name: promptResponse.componentName || process.argv[3],
description: promptResponse.inputDescription || 'I was created from Strike-CLI'
}
};
return userInputObj;
}
function saveUserInput(username, password){
db.set('credentials[0]', { id: 1, username: username, password: password})
.value();
}
function upsertFiles(bundleId, inputArgs, callback){
if(isEvent(inputArgs.name)){
upsertComponentFile(bundleId, inputArgs, 'EVENT');
} else if(isToken(inputArgs.name)){
upsertTokenFile(bundleId, inputArgs, 'TOKENS');
} else{
var fileTypes = ['COMPONENT', 'CONTROLLER', 'HELPER', 'RENDERER', 'EVENT', 'STYLE'];
fileTypes.forEach(function(fileType){
upsertComponentFile(bundleId, inputArgs, fileType);
});
}
callback();
}
function createApexClass(bundle, callback){
console.log('upserting ' + bundle);
fs.readFile(process.cwd() + '/strike-components/' + bundle, 'utf8', function(err, contents){
conn.tooling.sobject('ApexClass').create({
body: contents
}, function(err){
if(err){
if(err.errorCode === 'UNKNOWN_EXCEPTION'){
console.log(bundle + ' was skipped because an admin operation already in progress. Please try again in a few minutes');
callback();
} else if(err.errorCode === 'DUPLICATE_VALUE'){
async.waterfall([
function queryForApexClassId(callback){
conn.tooling.query('SELECT Id, Name FROM ApexClass WHERE Name = ' + '\'' + bundle.substring(0, bundle.length - 4) + '\'', function(err, res){
if (err) { return console.error(chalk.red(err)); }
var fileId = res.records[0].Id;
callback(null, fileId) ;
});
},
function createMetaDataContainer(fileId, callback){
conn.tooling.sobject('MetaDataContainer').create({
Name: generateRandomName('Container')
}, function(err, res){
if (err) { return console.error(chalk.red(err)); }
var metaDataContainerId = res.id;
callback(null, fileId, metaDataContainerId);
});
},
function createApexClassMember(fileId, metaDataContainerId, callback){
conn.tooling.sobject('ApexClassMember').create({
MetaDataContainerId: metaDataContainerId,
ContentEntityId: fileId,
Body: contents
}, function(err, res){
if (err) { return console.error(chalk.red(err)); }
callback(null, metaDataContainerId);
});
},
function createContainerAsyncRequest(metaDataContainerId, callback){
conn.tooling.sobject('containerAsyncRequest').create({
MetaDataContainerId: metaDataContainerId,
isCheckOnly: 'false'
}, function(err, res){
if (err) {
console.log(chalk.red(typeof(err)));
console.log(chalk.red(err));
}
callback(null, res);
});
}
], function(err){
if (err) { return console.error(chalk.red(err)); }
console.log(bundle + ' was updated');
callback();
});
}
} else{
console.log(bundle + ' was created');
callback();
}
});
});
}
function createAuraDefinitionBundle(inputArgs, callback){
conn.tooling.sobject('AuraDefinitionBundle').create({
Description: inputArgs.description, // my description
DeveloperName: inputArgs.name,
MasterLabel: inputArgs.name,
ApiVersion:'40.0'
}, function(err, res){
var bundleId;
if(err){
if(err.errorCode === 'DUPLICATE_DEVELOPER_NAME'){
conn.tooling.query('Select Id, DeveloperName FROM AuraDefinitionBundle WHERE DeveloperName =\'' + inputArgs.name + '\'', function(err, res){
if (err) { return console.error(chalk.red(err)); }
console.log(res.records[0].DeveloperName + ' bundle already exists, updating its respective files...');
bundleId = res.records[0].Id;
upsertFiles(bundleId, inputArgs, function(){
callback();
});
});
} else{
{ return console.error(chalk.red(err)); }
}
} else{
console.log(inputArgs.name + ' bundle was created');
bundleId = res.id;
upsertFiles(bundleId, inputArgs, function(){
callback();
});
}
});
}
function isEvent(name){
return name.substring(0,10) === 'strike_evt';
}
function isToken(name){
return name === 'defaultTokens';
}
function createStaticResource(name){
fs.readFile(process.cwd() + '/strike-components/' + name + '.resource', 'utf8', function(err, contents){
if(err){
console.log(err);
} else {
var encodedBody = new Buffer(contents).toString('base64');
}
conn.tooling.sobject('StaticResource').create({
body: encodedBody,
ContentType: 'text/javascript',
CacheControl: 'Public',
Name: name
}, function(err){
if(err){
if(err.errorCode === 'DUPLICATE_DEVELOPER_NAME'){
console.log(name + ' static resource already exists');
}
}
});
});
}
function upsertTokenFile(bundleId, inputArgs, type){
fs.readFile(process.cwd() + '/strike-components/' + inputArgs.name + '/' + inputArgs.name + fileExtensionMap[type], 'utf8', function(err, contents){
if(validContent(contents)){
var strikeContents = contents;
conn.tooling.sobject('AuraDefinition').create({
AuraDefinitionBundleId: bundleId,
DefType: type,
Format: fileFormatMap[type],
Source: strikeContents
}, function(err){
if (err) {
if(err.errorCode === 'DUPLICATE_VALUE'){
conn.tooling.query('Select Id, AuraDefinitionBundleId, DefType, SOURCE FROM AuraDefinition WHERE AuraDefinitionBundleId =\'' + bundleId + '\'' + 'AND DefType =\'' + type + '\'', function(err, res){
if (err) { return console.error(chalk.red(err)); }
var fileId = res.records[0].Id;
var remoteContents = res.records[0].Source;
var linesToInsertArray = tokenParser.createLinesToInsert(strikeContents, remoteContents);
if(!linesToInsertArray.length == 0){
var mergedTokenFile = mergeTokenFile(remoteContents, linesToInsertArray);
conn.tooling.sobject('AuraDefinition').update({Id: fileId, Source: mergedTokenFile}, function(err){
if (err) {
console.error(err);
} else {
console.log(type + ' file for ' + inputArgs.name + ' ' + type + ' was updated');
}
});
}
});
} else {
return console.error(err);
}
} else{
console.log(type + ' file for ' + inputArgs.name + ' ' + type + ' was created');
}
});
}
});
}
function upsertComponentFile(bundleId, inputArgs, type){
fs.readFile(process.cwd() + '/strike-components/' + inputArgs.name + '/' + inputArgs.name + fileExtensionMap[type], 'utf8', function(err, contents){
if(validContent(contents)){
conn.tooling.sobject('AuraDefinition').create({
AuraDefinitionBundleId: bundleId,
DefType: type,
Format: fileFormatMap[type],
Source: contents
}, function(err){
if (err) {
if(err.errorCode === 'DUPLICATE_VALUE'){
conn.tooling.query('Select Id, AuraDefinitionBundleId, DefType FROM AuraDefinition WHERE AuraDefinitionBundleId =\'' + bundleId + '\'' + 'AND DefType =\'' + type + '\'', function(err, res){
if (err) { return console.error(chalk.red(err)); }
var fileId = res.records[0].Id;
conn.tooling.sobject('AuraDefinition').update({Id: fileId, Source: contents}, function(err){
if (err) {
console.error(err);
} else {
console.log(type + ' file for ' + inputArgs.name + ' ' + type + ' was updated');
}
});
});
} else {
return console.error(err);
}
} else{
console.log(type + ' file for ' + inputArgs.name + ' ' + type + ' was created');
}
});
}
});
}
function mergeTokenFile (originalContent, linesToInsertArray) {
var regexForFooter = /<\/aura:tokens>/g;
var mergedSource = originalContent.replace(regexForFooter, linesToInsertArray.join(''));
return mergedSource;
}
function generateRandomName(prefix){
var date = new Date();
var dateComponents = [
date.getSeconds(),
date.getMilliseconds()
];
var randomInt = dateComponents.join('');
var randomName = prefix + randomInt;
return randomName;
}
function configureHelpCommand(){
drawScreen();
commander.__proto__.addImplicitHelpCommand = function () {} //this is to prevent the implicit help command. The documenation for this does not have another way to prevent this behaviour
commander
.usage('<command> [component_name]')
.command('install', 'upsert specified component and dependencies to your org')
.command('update', 'upsert specified component and dependencies to your org')
.command('upsert', 'upsert specified component and dependencies to your org')
.command('connect', 'connect/store credentials')
.command('disconnect', 'disconnects stored credentials');
commander.on('--help', function(){
console.log(' -s, --sandbox login to a sandbox org instead');
console.log('');
console.log(' Supported Components:');
console.log('');
Object.keys(dependencyMap).forEach(function(key){
console.log(' <' + key + '>');
});
});
commander.parse(process.argv);
}
function verboseFlagExists() {
return process.argv.indexOf('-v') > -1 || process.argv.indexOf('--verbose') > -1;
}
function sandboxFlagExists() {
return process.argv.indexOf('-s') > -1 || process.argv.indexOf('--sandbox') > -1;
}
function log(text){
if(verboseFlagExists()){
console.log(text);
}
}