/
titanium.js
507 lines (449 loc) Β· 15.5 KB
/
titanium.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
/**
* Titanium SDK Library for Node.js
* Copyright (c) 2012 by Appcelerator, Inc. All Rights Reserved.
* Please see the LICENSE file for information about licensing.
*/
var fs = require('fs'),
path = require('path'),
async = require('async'),
appc = require('node-appc'),
i18n = appc.i18n(__dirname),
__ = i18n.__,
__n = i18n.__n,
spawn = require('child_process').spawn,
afs = appc.fs,
version = appc.version,
manifest = appc.pkginfo.manifest(module),
platformAliases = {
// add additional aliases here for new platforms
'ipad': 'iphone',
'ios': 'iphone'
};
exports.i18n = require('./i18n');
exports.jss = require('./jss');
exports.tiappxml = require('./tiappxml');
exports.legacy = require('./legacy');
exports.manifest = manifest;
exports.targetPlatforms = manifest.platforms.map(function (p) {
return p == 'iphone' ? 'ios' : p;
}).sort();
exports.availablePlatforms = (manifest.platforms || []).sort();
exports.availablePlatformsNames = function (platforms) {
Object.keys(platformAliases).forEach(function (alias) {
if (platforms.indexOf(platformAliases[alias]) != -1) {
platforms.push(alias);
}
});
return platforms.sort();
}(manifest.platforms || []);
exports.commonOptions = function (logger, config) {
return {
sdk: {
abbr: 's',
desc: __('Titanium SDK version to use to bootstrap SDK-level commands and parse the tiapp.xml; actual Titanium SDK used determined by %s in the tiapp.xml', '<sdk-version>'.cyan)
},
'log-level': {
callback: function (value) {
logger.levels.hasOwnProperty(value) && logger.setLevel(value);
},
desc: __('minimum logging level'),
default: config.cli.logLevel || 'trace',
hint: __('level'),
values: logger.getLevels()
}
};
};
exports.platformOptions = function (logger, config, cli, commandName, finished) {
var result = {};
if (!commandName) {
finished(result);
return;
}
function set(obj, title, platform) {
// add the platform and title to the options and flags
['options', 'flags'].forEach(function (type) {
if (obj[type]) {
result[platform] || (result[platform] = {
platform: platform,
title: title || platform
});
result[platform][type] = obj[type];
}
});
}
// for each platform, fetch their specific flags/options
async.parallel(manifest.platforms.map(function (platform) {
return function (callback) {
var platformDir = path.join(path.dirname(module.filename), '..', '..', '..', platform),
platformCommand = path.join(platformDir, 'cli', 'commands', '_' + commandName + '.js'),
command,
conf,
title;
if (!afs.exists(platformCommand)) return callback();
command = require(platformCommand);
if (!command || !command.config) return callback();
// try to get the platform specific configuration
conf = command.config(logger, config, cli);
try {
// try to read a title from the platform's package.json
title = JSON.parse(fs.readFileSync(path.join(platformDir, 'package.json'))).title;
} catch (e) {}
if (typeof conf == 'function') {
// async callback
conf(function (obj) {
set(obj, title, platform);
callback();
});
return;
}
set(conf, title, platform);
callback();
};
}), function () {
finished(result);
});
};
exports.validateProjectDir = function(logger, cli, argv, name) {
var dir = argv[name] || (process.env.SOURCE_ROOT ? path.join(process.env.SOURCE_ROOT, '..', '..') : '.'),
projectDir = argv[name] = appc.fs.resolvePath(dir);
if (!appc.fs.exists(projectDir)) {
logger.banner();
logger.error(__('Project directory does not exist') + '\n');
process.exit(1);
}
var tiapp = path.join(projectDir, 'tiapp.xml');
while (!appc.fs.exists(tiapp) && tiapp.split(path.sep).length > 2) {
projectDir = argv[name] = path.dirname(projectDir);
tiapp = path.join(projectDir, 'tiapp.xml');
}
if (tiapp.split(path.sep).length == 2) {
logger.banner();
logger.error(__('Invalid project directory "%s"', dir) + '\n');
dir == '.' && logger.log(__("Use the %s property to specify the project's directory", '--project-dir'.cyan) + '\n');
process.exit(1);
}
// load the tiapp.xml
cli.tiapp = new exports.tiappxml(path.join(projectDir, 'tiapp.xml'));
};
exports.validateTiappXml = function (logger, tiapp) {
if (!tiapp.id) {
logger.error(__('tiapp.xml is missing the <id> element'));
logger.error(__('The app id must consist of letters, numbers, and underscores.'));
logger.error(__('Note: Android does not allow dashes and iOS does not allow underscores.'));
logger.error(__('The first character must be a letter or underscore.'));
logger.error(__("Usually the app id is your company's reversed Internet domain name. (i.e. com.example.myapp)") + '\n');
process.exit(1);
}
if (!/^([a-zA-Z_]{1}[a-zA-Z0-9_-]*(\.[a-zA-Z0-9_-]*)*)$/.test(tiapp.id)) {
logger.error(__('tiapp.xml contains an invalid app id "%s"', tiapp.id));
logger.error(__('The app id must consist only of letters, numbers, dashes, and underscores.'));
logger.error(__('Note: Android does not allow dashes and iOS does not allow underscores.'));
logger.error(__('The first character must be a letter or underscore.'));
logger.error(__("Usually the app id is your company's reversed Internet domain name. (i.e. com.example.myapp)") + '\n');
process.exit(1);
}
if (!tiapp.name) {
logger.error(__('tiapp.xml is missing the <name> element'));
logger.error(__('The project name must consist of letters, numbers, dashes, and underscores.'));
logger.error(__('The first character must be a letter.') + '\n');
process.exit(1);
}
if (!tiapp.guid) {
logger.error(__('tiapp.xml is missing the <guid> element'));
logger.error(__('The guid must be in the format XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX and consist of letters and numbers.') + '\n');
logger.log(__('If you need a new guid, below are 5 freshly generated new ones that you can choose from:'));
for (var i = 0, uuid = require('node-uuid'); i < 5; i++) {
logger.log(' ' + uuid.v4().cyan);
}
logger.log();
process.exit(1);
}
if (!/^[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}$/.test(tiapp.guid)) {
logger.error(__('tiapp.xml contains an invalid guid "%s"', tiapp.guid));
logger.error(__('The guid must be in the format XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX and consist of letters and numbers.') + '\n');
logger.log(__('If you need a new guid, below are 5 freshly generated new ones that you can choose from:'));
for (var i = 0, uuid = require('node-uuid'); i < 5; i++) {
logger.log(' ' + uuid.v4().cyan);
}
logger.log();
process.exit(1);
}
tiapp.version || (tiapp.version = '1.0');
if (!/^\d+(\.\d+(\.\d+(\..+)?)?)?$/.test(tiapp.version)) {
logger.error(__('tiapp.xml contains an invalid version "%s"', tiapp.version));
logger.error(__('The version may only contist of letters, numbers, dashes, underscores, pluses, and spaces.') + '\n');
process.exit(1);
}
if ((''+tiapp.version).charAt(0) == '0') {
logger.warn(__('tiapp.xml contains an invalid version "%s"', tiapp.version));
logger.warn(__('The app version major number must be greater than zero.'));
}
};
exports.validAppId = function (id) {
var words = {
'abstract': 1,
'assert': 1,
'boolean': 1,
'break': 1,
'byte': 1,
'case': 1,
'catch': 1,
'char': 1,
'class': 1,
'const': 1,
'continue': 1,
'default': 1,
'do': 1,
'double': 1,
'else': 1,
'enum': 1,
'extends': 1,
'false': 1,
'final': 1,
'finally': 1,
'float': 1,
'for': 1,
'goto': 1,
'if': 1,
'implements': 1,
'import': 1,
'instanceof': 1,
'int': 1,
'interface': 1,
'long': 1,
'native': 1,
'new': 1,
'null': 1,
'package': 1,
'private': 1,
'protected': 1,
'public': 1,
'return': 1,
'short': 1,
'static': 1,
'strictfp': 1,
'super': 1,
'switch': 1,
'synchronized': 1,
'this': 1,
'throw': 1,
'throws': 1,
'transient': 1,
'true': 1,
'try': 1,
'void': 1,
'volatile': 1,
'while': 1
},
parts = id.split('.'),
i = 0,
l = parts.length;
for (; i < l; i++) {
if (words[parts[i]]) {
return false;
}
}
return true;
};
exports.loadPlugins = function (logger, cli, config, projectDir) {
// find all hooks for active plugins
appc.tiplugin.find(cli.tiapp.plugins, projectDir, config, logger, function (plugins) {
if (plugins.missing.length) {
logger.error(__('Could not find all required Titanium plugins:'))
plugins.missing.forEach(function (m) {
logger.error(' id: ' + m.id + '\t version: ' + m.version);
});
logger.log();
process.exit(1);
}
if (plugins.found.length) {
plugins.found.forEach(function (plugin) {
// we don't support plugins that have both a plugin.py and new .js files
plugin.legacy || cli.scanHooks(afs.resolvePath(plugin.pluginPath, 'hooks'));
});
} else {
logger.debug(__('No project level plugins to load'));
}
});
if (cli.hooks.loadedFilenames.length) {
// display all hooks for debugging
logger.debug(__('Loaded plugin hooks:'));
cli.hooks.loadedFilenames.forEach(function (f) {
logger.debug(f.cyan);
});
}
if (cli.hooks.incompatibleFilenames.length) {
// display all hooks for debugging
logger.debug(__('Incompatible plugin hooks:'));
cli.hooks.incompatibleFilenames.forEach(function (f) {
logger.debug(f.cyan);
});
}
if (cli.hooks.erroredFilenames && cli.hooks.erroredFilenames.length) {
logger.debug(__('Bad plugin hooks that failed to load:'));
cli.hooks.erroredFilenames.forEach(function (f) {
logger.debug(f.cyan);
});
}
};
exports.validateCorrectSDK = function (logger, config, cli, commandName) {
// tiapp.xml should exist by the time we get here
var sdk = cli.tiapp['sdk-version'];
if (cli.argv.legacy !== true && (!sdk || version.eq(sdk, manifest.version))) {
return true;
}
// check the project's preferred sdk is even installed
if (sdk == '__global__' || !cli.env.sdks[sdk]) {
logger.banner();
logger.error(__("Unable to compile project because the 'sdk-version' in the tiapp.xml is not installed") + '\n');
logger.log(__("The project's %s is currently set to %s, which is not installed.", 'sdk-version'.cyan, sdk.cyan) + '\n');
logger.log(__("Update the %s in the tiapp.xml to one of the installed Titaniums SDKs:", 'sdk-version'.cyan));
Object.keys(cli.env.sdks).sort().forEach(function (ver) {
if (ver != '__global__') {
logger.log(' ' + ver.cyan);
}
});
logger.log(__("or run '%s' to download and install Titanium SDK %s", ('titanium sdk install ' + sdk).cyan, sdk) + '\n');
process.exit(1);
}
var args = cli.argv.$_,
p = args.indexOf('--sdk'),
platform = exports.resolvePlatform(cli.argv.platform),
cmd = [],
emulatorCmd = [],
cmdRoot,
hideBanner = false;
if (p != -1) {
args.splice(p, 2);
}
if (cli.argv.legacy || version.lt(sdk, '2.2.0')) { // technically, there is no 2.2, it was released as 3.0
cmdRoot = 'python';
exports.legacy.constructLegacyCommand(cli, cli.tiapp, platform, cmd, emulatorCmd);
} else {
// 3.0.0's iOS build does not like it if node has a full path, so we hope they have node in the path
cmdRoot = version.gte(sdk, '3.0.2') ? (process.execPath || 'node') : 'node';
cmd = [cli.argv.$0.split(' ').slice(1), commandName, '--sdk', sdk];
hideBanner = true;
function copyArgs(ctx) {
if (ctx.flags) {
Object.keys(ctx.flags).forEach(function (f) {
if (cli.argv.hasOwnProperty(f)) {
cmd.push('--' + (!!cli.argv[f] ? '' : 'no-') + f);
}
});
}
if (ctx.options) {
Object.keys(ctx.options).forEach(function (o) {
if (o != 'sdk' && cli.argv.hasOwnProperty(o)) {
cmd.push('--' + o);
cmd.push(cli.argv[o]);
}
});
}
}
try {
var ctx = cli.cmds[commandName][cli.argv.sdk].__global__;
copyArgs(ctx);
ctx.platforms && ctx.platforms[platform] && copyArgs(ctx.platforms[platform]);
} catch (ex) {}
}
// fork or die
if (config.cli.failOnWrongSDK) {
logger.banner();
logger.error(__('Unable to compile a %s project with Titanium SDK %s', sdk, manifest.version) + '\n');
logger.log(__("Run '%s' to build using the correct Titanium SDK or update the %s in the tiapp.xml to the current Titaniums SDK: %s",
(cmdRoot + ' "' + cmd.join('" "') + '"').cyan, 'sdk-version'.cyan, manifest.version.cyan) + '\n');
process.exit(1);
}
if (emulatorCmd.length > 0) {
// console.log('Forking correct SDK command: ' + ( cmdRoot + ' ' + emulatorCmd.join(' ') ).cyan + '\n');
spawn(cmdRoot, emulatorCmd, {});
}
if (cli.argv.legacy) {
logger.info(__('Forking legacy SDK command: %s', (cmdRoot + ' "' + cmd.join('" "') + '"').cyan));
} else {
logger.info(__('tiapp.xml <sdk-version> set to %s, but current Titanium SDK set to %s', sdk.cyan, manifest.version.cyan));
logger.info(__('Forking correct SDK command: %s', (cmdRoot + ' ' + cmd.join(' ')).cyan));
}
hideBanner && cmd.push('--no-banner');
spawn(cmdRoot, cmd, {
stdio: 'inherit'
}).on('exit', function (code, signal) {
code && process.exit(code);
});
};
exports.validateAppJsExists = function (projectDir, logger) {
if (!afs.exists(projectDir, 'Resources')) {
logger.error(__('Resources directory not found') + '\n');
logger.log(__("Ensure the \"Resources\" directory exists and contains an \"app.js\" file.") + '\n');
process.exit(1);
}
if (!afs.exists(projectDir, 'Resources', 'app.js')) {
logger.error(__('app.js not found') + '\n');
logger.log(__("Ensure the \"app.js\" file exists in your project's \"Resources\" directory.") + '\n');
process.exit(1);
}
};
exports.validatePlatformOptions = function (logger, config, cli, commandName) {
var platform = exports.resolvePlatform(cli.argv.platform),
platformCommand = path.join(path.dirname(module.filename), '..', '..', '..', manifest.platforms[manifest.platforms.indexOf(platform)], 'cli', 'commands', '_' + commandName + '.js');
if (afs.exists(platformCommand)) {
var command = require(platformCommand),
result = command && command.validate ? command.validate(logger, config, cli) : null;
if (result === false) {
return false;
}
}
};
exports.scrubPlatforms = function (platforms) {
var scrubbed = {}, // distinct list of un-aliased platforms
original = {},
bad = {};
platforms.toLowerCase().split(',').forEach(function (platform) {
var name = platformAliases[platform] || platform;
// if name is falsey, then it's invalid anyways
if (name) {
if (manifest.platforms.indexOf(name) == -1) {
bad[platform] = 1;
} else {
scrubbed[name] = 1;
original[platform] = 1;
}
}
});
return {
scrubbed: Object.keys(scrubbed).sort(), // distinct list of un-aliased platforms
original: Object.keys(original).sort(),
bad: Object.keys(bad).sort()
};
};
exports.resolvePlatform = function (platform) {
return platformAliases[platform] || platform;
};
exports.filterPlatforms = function (platform) {
platform = platformAliases[platform] || platform;
return exports.availablePlatformsNames.filter(function (name) {
return name != platform;
});
};
exports.validatePlatform = function (logger, argv, name) {
var platform = name ? argv[name] : argv,
p = argv[name] = platformAliases[platform] || platform;
if (!p || manifest.platforms.indexOf(p) == -1) {
logger.banner();
logger.error(__('Invalid platform "%s"', platform) + '\n');
appc.string.suggest(platform, exports.targetPlatforms, logger.log);
logger.log(__('Available platforms for SDK version %s:', manifest.version));
exports.targetPlatforms.forEach(function (p) {
logger.log(' ' + p.cyan);
});
logger.log();
process.exit(1);
}
};
exports.validatePlatforms = function (logger, platforms) {
platforms.forEach(function (p) {
exports.validatePlatform(logger, p);
});
return platforms;
};