-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathinstall.js
More file actions
525 lines (459 loc) · 16.9 KB
/
install.js
File metadata and controls
525 lines (459 loc) · 16.9 KB
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
// -----------------------------------------------------------
// version 1.09
// -----------------------------------------------------------
"use strict";
var debugging = false;
var fs = require('fs');
var cp = require('child_process');
var path = require('path');
var isRanFromNativeScript = fs.existsSync("../../app/App_Resources");
var hasNativeScript = fs.existsSync("../../nativescript");
// Figure out angular Seed Path for symlink...
var angularSeedPath = '../../src/';
var seeds = ['client', 'app'];
var seedId = 0;
// Search for the actual seed, depending on where we are run from
for (var i=0;i<seeds.length;i++) {
if (fs.existsSync(angularSeedPath+seeds[i])) {
seedId = i; break;
}
}
angularSeedPath += seeds[seedId] + "/";
var nativescriptClientPath = '../../nativescript/app/' + seeds[seedId] + "/";
if (debugging) {
console.log("Path is:", angularSeedPath, nativescriptClientPath);
}
// Root SymLink Code for Windows
if (process.argv.length > 2) {
if (process.argv[2] === 'symlink') {
createRootSymLink();
console.log("Created Symlink");
}
return 0;
}
if (!hasNativeScript && !isRanFromNativeScript) {
console.log("Installing NativeScript Angular 2 Template...");
cp.execSync('tns create nativescript --template https://github.com/NativeScript/template-hello-world-ng', {cwd: '../..'});
console.log("Installing NativeScript support files...");
cp.execSync('npm install', {cwd: '../../nativescript'});
console.log("Installing support files");
if (process.platform === 'darwin') {
try {
cp.execSync('npm install image-to-ascii-cli', {cwd: '../..'});
}
catch (Err) {
console.log("Install Error", Err);
}
}
console.log("Configuring...");
if (debugging) {
cp.execSync('tns plugin add ../node_modules/nativescript-ng2-magic', {cwd: '../../nativescript'});
} else {
cp.execSync('tns plugin add nativescript-ng2-magic', {cwd: '../../nativescript'});
}
// remove sample component
if (fs.existsSync('../../nativescript/app/app.component.ts')) {
console.log("Removing sample component");
fs.unlinkSync('../../nativescript/app/app.component.ts');
}
if (fs.existsSync('../../nativescript/app/app.component.html')) {
console.log("Removing sample component html");
fs.unlinkSync('../../nativescript/app/app.component.html');
}
// We need to create a symlink
try {
createSymLink();
} catch (err) {
if (debugging) {
console.log("Symlink error: ", err);
}
// Failed, which means they weren't running root; so lets try to get root
AttemptRootSymlink();
}
// Might silent fail on OSX, so we have to see if it exists
if (!fs.existsSync(nativescriptClientPath)) {
AttemptRootSymlink();
}
// This does not look good on windows; windows ansi support in node sucks... So we aren't going to do this in windows
if (process.platform === "darwin") {
// image to ascii uses GM which may not be installed, so if it isn't installed; don't print the error message
try {
var ascii = cp.execSync('image-to-ascii -i https://cdn.filestackcontent.com/XXMT4f8S8OGngNsJj0pr', {cwd: '../image-to-ascii-cli/bin/'}).toString();
if (ascii.length > 30) {
console.log(ascii);
}
}
catch (err) {
// Do Nothing; if the site can't be resolved; we don't want to fail the script
}
}
displayFinalHelp();
if (!fs.existsSync(nativescriptClientPath)) {
console.log("We were unable to create a symlink - from -");
console.log(" ", resolve(angularSeedPath), " - to - ");
console.log(" ", resolve(nativescriptClientPath));
console.log("If you don't create this symlink, you will have to manually copy the code each time you change it.");
}
}
if (isRanFromNativeScript) {
if (!fs.existsSync('installed.ns') ) {
fs.writeFileSync('installed.ns', 'installed');
fixTsConfig();
fixRefFile();
fixNativeScriptPackage();
fixAngularPackage();
fixMainFile( figureOutRootComponent());
// when being run from inside {N} app, the directory is different
var srcRoot = '../../../src/';
for (var i=0;i<seeds.length;i++) {
if (fs.existsSync(srcRoot + seeds[i])) {
seedId = i; break;
}
}
fixGitIgnore('nativescript/app/' + seeds[seedId]);
fixGitIgnore('nativescript/app/node_modules');
fixGitIgnore('nativescript/app/platforms');
console.log("Completed Install");
} else {
console.log("We have already been installed in the NativeScript app as a plugin.");
return 0;
}
}
return 0;
/**
* Searches for the bootstrap file until it finds one....
* @returns {string}
*/
function figureOutRootComponent() {
var rootComponents = ['../../../src/app/app.module.ts', '../../../src/app.ts', '../../../boot.ts', '../../../src/main.ts'];
for (var i=0;i<rootComponents.length; i++) {
if (fs.existsSync(rootComponents[i])) {
var result = processBootStrap(rootComponents[i]);
if (result) { return result; }
}
}
// Return a default component, if we can't find one...
return {
name: 'AppComponent',
path: './client/components/app.component'
};
}
/**
* Parses the bootstrap to figure out the default bootstrap component
* @param file
* @returns {*}
*/
function processBootStrap(file) {
var data = fs.readFileSync(file).toString();
var idx = data.indexOf('bootstrap(');
if (idx === -1) { return null; }
else { idx+=10; }
var odx1 = data.indexOf(',', idx);
var odx2 = data.indexOf(')', idx);
if (odx2 < odx1 && odx2 !== -1 || odx1 === -1) { odx1 = odx2; }
if (odx1 === -1) { return null; }
var componentRef = data.substring(idx, odx1);
var exp = "import\\s+\\{("+componentRef+")\\}\\s+from+\\s+[\'|\"](\\S+)[\'|\"][;?]";
if (debugging) {
console.log("Searching for", exp);
}
var result = function (r) {
return {
name: r[1],
path: r[r.length - 1]
};
};
//noinspection JSPotentiallyInvalidConstructorUsage
var r = RegExp(exp, 'i').exec(data);
if (r === null || r.length <= 1) {
// check if using current style guide with spaces
exp = "import\\s+\\{\\s+("+componentRef+")\\,\\s+([A-Z]{0,300})\\w+\\s+\\}\\s+from+\\s+[\'|\"](\\S+)[\'|\"][;?]";
if (debugging) {
console.log("Searching for", exp);
}
r = RegExp(exp, 'i').exec(data);
if (r === null || r.length <= 1) {
// try just spaces with no angular cli style (, environment) etc.
exp = "import\\s+\\{\\s+(" + componentRef + ")\\s+\\}\\s+from+\\s+[\'|\"](\\S+)[\'|\"][;?]";
if (debugging) {
console.log("Searching for", exp);
}
r = RegExp(exp, 'i').exec(data);
if (r !== null && r.length > 1) {
return result(r);
}
} else {
// angular cli
return result(r);
}
return null;
}
return result(r);
}
/**
* This will attempt to run the install script as root to make a symlink
*
*/
function AttemptRootSymlink() {
if (process.platform === 'win32') {
var curPath = resolve("./");
if (debugging) {
console.log("RootSymlink Base path is", curPath);
}
cp.execSync("powershell -Command \"Start-Process 'node' -ArgumentList '"+curPath+"/install.js symlink' -verb runas\"");
} else {
console.log("To automatically create a SymLink between your web app and NativeScript, we need root for a second.");
cp.execSync("sudo "+process.argv[0] + " " + process.argv[1] +" symlink");
}
}
/**
* Create the symlink when running as root
*/
function createRootSymLink() {
var li1 = process.argv[1].lastIndexOf('\\'), li2 = process.argv[1].lastIndexOf('/');
if (li2 > li1) { li1 = li2; }
var AppPath = process.argv[1].substring(0,li1);
var p1 = resolve(AppPath + "/" + nativescriptClientPath);
var p2 = resolve(AppPath + "/" + angularSeedPath);
if (debugging) {
console.log("Path: ", p1, p2);
}
fs.symlinkSync(p2,p1,'junction');
}
/**
* Create Symlink
*/
function createSymLink() {
if (debugging) {
console.log("Attempting to Symlink", angularSeedPath, nativescriptClientPath);
}
fs.symlinkSync(resolve(angularSeedPath),resolve(nativescriptClientPath),'junction');
}
/**
* This fixes the TS Config file in the nativescript folder
*/
function fixTsConfig() {
var tsConfig={}, tsFile = '../../tsconfig.json';
if (fs.existsSync(tsFile)) {
tsConfig = require(tsFile);
}
if (!tsConfig.compilerOptions || !tsConfig.compilerOptions.typeRoots) {
tsConfig.compilerOptions = {
target: "es5",
module: "commonjs",
declaration: false,
removeComments: true,
noLib: false,
emitDecoratorMetadata: true,
experimentalDecorators: true,
lib: [
"dom"
],
sourceMap: true,
pretty: true,
allowUnreachableCode: false,
allowUnusedLabels: false,
noImplicitAny: false,
noImplicitReturns: true,
noImplicitUseStrict: false,
noFallthroughCasesInSwitch: true,
typeRoots: [
"node_modules/@types",
"node_modules"
],
types: [
"jasmine"
]
};
}
// See: https://github.com/NativeScript/nativescript-angular/issues/205
// tsConfig.compilerOptions.noEmitHelpers = false;
// tsConfig.compilerOptions.noEmitOnError = false;
if (!tsConfig.exclude) {
tsConfig.exclude = [];
}
if (tsConfig.exclude.indexOf('node_modules') === -1) {
tsConfig.exclude.push('node_modules');
}
if (tsConfig.exclude.indexOf('platforms') === -1) {
tsConfig.exclude.push('platforms');
}
fs.writeFileSync(tsFile, JSON.stringify(tsConfig, null, 4), 'utf8');
}
/**
* This fixes the references file to work with TS 2.0 in the nativescript folder
*/
function fixRefFile() {
var existingRef='', refFile = '../../references.d.ts';
if (fs.existsSync(refFile)) {
existingRef = fs.readFileSync(refFile).toString();
}
if (existingRef.indexOf('typescript/lib/lib.d.ts') === -1) {
// has not been previously modified
var fix = '/// <reference path="./node_modules/tns-core-modules/tns-core-modules.d.ts" />\n' +
'/// <reference path="./node_modules/typescript/lib/lib.d.ts" />\n';
fs.writeFileSync(refFile, fix, 'utf8');
}
}
/**
* Fix the NativeScript Package file
*/
function fixNativeScriptPackage() {
var packageJSON = {}, packageFile = '../../package.json';
packageJSON.name = "NativeScriptApp";
packageJSON.version = "0.0.0";
// var AngularJSON = {};
if (fs.existsSync(packageFile)) {
packageJSON = require(packageFile);
} else {
console.log("This should not happen, your are missing your package.json file!");
return;
}
// if (fs.existsSync('../angular2/package.json')) {
// AngularJSON = require('../angular2/package.json');
// } else {
// // Copied from the Angular2.0.0-beta-16 package.json, this is a fall back
// AngularJSON.peerDependencies = {
// "es6-shim": "^0.35.0",
// "reflect-metadata": "0.1.2",
// "rxjs": "5.0.0-beta.6",
// "zone.js": "^0.6.12"
// };
// }
packageJSON.nativescript['tns-ios'] = { version: "2.3.0" };
packageJSON.nativescript['tns-android'] = {version: "2.3.0" };
// Copy over all the Peer Dependencies
// for (var key in AngularJSON.peerDependencies) {
// if (AngularJSON.peerDependencies.hasOwnProperty(key)) {
// packageJSON.dependencies[key] = AngularJSON.peerDependencies[key];
// }
// }
// TODO: Can we get these from somewhere rather than hardcoding them, maybe need to pull/download the package.json from the default template?
if (!packageJSON.devDependencies) {
packageJSON.devDependencies = {};
}
packageJSON.devDependencies["@types/jasmine"] = "^2.5.35";
packageJSON.devDependencies["babel-traverse"] = "6.12.0";
packageJSON.devDependencies["babel-types"] = "6.11.1";
packageJSON.devDependencies.babylon = "6.8.4";
packageJSON.devDependencies.filewalker = "0.1.2";
packageJSON.devDependencies.lazy = "1.0.11";
// packageJSON.devDependencies["nativescript-dev-typescript"] = "^0.3.2";
packageJSON.devDependencies.typescript = "^2.0.2";
fs.writeFileSync(packageFile, JSON.stringify(packageJSON, null, 4), 'utf8');
}
/**
* Fix the Angular Package
*/
function fixAngularPackage() {
var packageJSON = {}, packageFile = '../../../package.json';
if (fs.existsSync(packageFile)) {
packageJSON = require(packageFile);
} else {
console.log("This should not happen, your are missing your main package.json file!");
return;
}
if (!packageJSON.scripts) {
packageJSON.scripts = {};
}
packageJSON.scripts["start.ios"] = "cd nativescript && tns emulate ios";
packageJSON.scripts["start.livesync.ios"] = "cd nativescript && tns livesync ios --emulator --watch";
packageJSON.scripts["start.android"] = "cd nativescript && tns emulate android";
packageJSON.scripts["start.livesync.android"] = "cd nativescript && tns livesync android --emulator --watch";
fs.writeFileSync(packageFile, JSON.stringify(packageJSON, null, 4), 'utf8');
}
/**
* Fix the Main NativeScript File
* @param component
*/
function fixMainFile(component) {
var mainTS = '', mainFile = '../../app/main.ts';
if (fs.existsSync(mainFile)) {
mainTS = fs.readFileSync(mainFile).toString();
}
if (mainTS.indexOf('MagicService') === -1) {
// has not been previously modified
var fix = '// this import should be first in order to load some required settings (like globals and reflect-metadata)\n' +
'import { platformNativeScriptDynamic, NativeScriptModule } from "nativescript-angular/platform";\n' +
'import { NgModule } from "@angular/core";\n' +
'import { AppComponent } from "./app/app.component";\n' +
'\n' +
'@NgModule({\n' +
' declarations: [AppComponent],\n' +
' bootstrap: [AppComponent],\n' +
' imports: [NativeScriptModule],\n' +
'})\n' +
'class AppComponentModule {}\n\n' +
'platformNativeScriptDynamic().bootstrapModule(AppComponentModule);';
fs.writeFileSync(mainFile, fix, 'utf8');
}
}
/**
* Fix .gitignore
* @param path
*/
function fixGitIgnore(ignorePattern) {
var fileString = '', ignoreFile = '../../../.gitignore';
if (fs.existsSync(ignoreFile)) {
fileString = fs.readFileSync(ignoreFile).toString();
}
if (fileString.indexOf(ignorePattern) === -1) {
// has not been previously modified
var fix = fileString +
'\n' +
ignorePattern;
fs.writeFileSync(ignoreFile, fix, 'utf8');
}
}
/**
* Display final help screen!
*/
function displayFinalHelp()
{
console.log("-------------- Welcome to the Magical World of NativeScript -----------------------------");
console.log("To finish, follow this guide https://github.com/NathanWalker/nativescript-ng2-magic#usage");
console.log("After you have completed the steps in the usage guide, you can then:");
console.log("");
console.log("Run your app in the iOS Simulator with these options:");
console.log(" npm run start.ios");
console.log(" npm run start.livesync.ios");
console.log("");
console.log("Run your app in an Android emulator with these options:");
console.log(" npm run start.android");
console.log(" npm run start.livesync.android");
console.log("-----------------------------------------------------------------------------------------");
console.log("");
}
function splitPath(v) {
var x;
if (v.indexOf('/') !== -1) {
x = v.split('/');
} else {
x = v.split("\\");
}
return x;
}
function resolve(v) {
var cwdPath = splitPath(process.argv[1]);
// Kill the Script name
cwdPath.length = cwdPath.length - 1;
var resolvePath = splitPath(v);
// Eliminate a trailing slash/backslash
if (cwdPath[cwdPath.length-1] === "") { cwdPath.pop(); }
if (v[0] === '/' || v[0] === "\\") { cwdPath = []; }
for (var i=0;i<resolvePath.length;i++) {
if (resolvePath[i] === '.' || resolvePath[i] === "") { continue; }
if (resolvePath[i] === '..') { cwdPath.pop(); }
else { cwdPath.push(resolvePath[i]); }
}
if (process.platform === 'win32') {
var winResult = cwdPath.join("\\");
if (winResult[winResult.length-1] === "\\") { winResult = winResult.substring(0, winResult.length - 1); }
return winResult;
} else {
var result = cwdPath.join('/');
if (result[0] !== '/') { result = '/' + result; }
if (result[result.length-1] === '/') { result = result.substring(0, result.length - 1); }
return result;
}
}