-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathhyperloop.js
More file actions
1567 lines (1376 loc) · 53.3 KB
/
hyperloop.js
File metadata and controls
1567 lines (1376 loc) · 53.3 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
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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Hyperloop ®
* Copyright (c) 2015-2018 by Appcelerator, Inc.
* All Rights Reserved. This library contains intellectual
* property protected by patents and/or patents pending.
*/
'use strict';
module.exports = HyperloopiOSBuilder;
// Set this to enforce a ios-min-version
const IOS_MIN = '9.0';
// Set this to enforce a minimum Titanium SDK
const TI_MIN = '8.0.0';
// Set the iOS SDK minium
const IOS_SDK_MIN = '9.0';
const path = require('path');
const exec = require('child_process').exec;
const hm = require('hyperloop-metabase');
const metabase = hm.metabase;
const ModuleMetadata = metabase.ModuleMetadata;
const fs = require('fs-extra');
const chalk = require('chalk');
const async = require('async');
const HL = chalk.magenta.inverse('Hyperloop');
const semver = require('semver');
const babelParser = require('@babel/parser');
const t = require('@babel/types');
const traverse = require('@babel/traverse').default;
const generator = require('./generate');
/**
* The Hyperloop builder object. Contains the build logic and state.
* @class
* @constructor
* @param {Object} logger - The Titanium CLI logger.
* @param {Object} config - The Titanium CLI config.
* @param {Object} cli - The Titanium CLI instance.
* @param {Object} appc - Reference to node-appc.
* @param {Object} hyperloopConfig - Object containing a union of base, local, and user Hyperloop settings.
* @param {Builder} builder - A platform specific build command Builder object.
*/
function HyperloopiOSBuilder(logger, config, cli, appc, hyperloopConfig, builder) {
this.logger = logger;
this.config = config;
this.cli = cli;
this.appc = appc;
this.hyperloopConfig = hyperloopConfig || {};
this.hyperloopConfig.ios || (this.hyperloopConfig.ios = {});
this.builder = builder;
this.resourcesDir = path.join(builder.projectDir, 'Resources');
this.hyperloopBuildDir = path.join(builder.projectDir, 'build', 'hyperloop', 'ios');
this.hyperloopJSDir = path.join(this.hyperloopBuildDir, 'js');
this.hyperloopResourcesDir = path.join(this.builder.xcodeAppDir, 'hyperloop');
this.forceMetabase = false;
this.forceStubGeneration = false;
this.parserState = null;
this.frameworks = new Map();
this.systemFrameworks = new Map();
this.thirdPartyFrameworks = new Map();
this.includes = [];
this.swiftSources = [];
this.swiftVersion = '3.0';
this.jsFiles = {};
this.references = {};
this.usedFrameworks = new Map();
this.metabase = {};
this.nativeModules = {};
this.hasCocoaPods = false;
this.cocoaPodsBuildSettings = {};
this.cocoaPodsProducts = [];
this.headers = null;
// set our CLI logger
hm.util.setLog(builder.logger);
}
/**
* called for each JS resource to process them
*/
HyperloopiOSBuilder.prototype.compileJsFile = function (builder, callback) {
try {
const obj = builder.args[0];
const from = builder.args[1];
const to = builder.args[2];
this.processJSFile(obj, from, to, callback);
} catch (e) {
callback(e);
}
};
/**
* The main build logic.
* @param {Function} callback - A function to call after the logic finishes.
*/
HyperloopiOSBuilder.prototype.init = function init(callback) {
this.appc.async.series(this, [
'validate',
'setup',
'wireupBuildHooks',
'getSystemFrameworks',
'generateCocoaPods',
'processThirdPartyFrameworks',
'detectSwiftVersion'
], callback);
};
HyperloopiOSBuilder.prototype.run = function run(builder, callback) {
var start = Date.now();
this.logger.info('Starting ' + HL + ' assembly');
this.appc.async.series(this, [
'generateSourceFiles',
'generateSymbolReference',
'compileResources',
'generateStubs',
'copyHyperloopJSFiles',
'updateXcodeProject'
], function (err) {
if (err instanceof StopHyperloopCompileError) {
err = null;
}
this.logger.info('Finished ' + HL + ' assembly in ' + (Math.round((Date.now() - start) / 10) / 100) + ' seconds');
callback(err);
});
};
/**
* Validates the settings and environment.
*/
HyperloopiOSBuilder.prototype.validate = function validate() {
// hyperloop requires a minimum iOS SDK
if (!this.appc.version.gte(this.builder.iosSdkVersion, IOS_SDK_MIN)) {
this.logger.error('You cannot use the Hyperloop compiler with a version of iOS SDK older than ' + IOS_SDK_MIN);
this.logger.error('Please update to the latest iOS SDK and try again.\n');
process.exit(1);
}
// hyperloop requires a later version
if (!this.appc.version.gte(this.builder.titaniumSdkVersion, TI_MIN)) {
this.logger.error('You cannot use the Hyperloop compiler with a version of Titanium older than ' + TI_MIN);
this.logger.error('Set the value of <sdk-version> to a newer version in tiapp.xml.');
this.logger.error('For example:');
this.logger.error(' <sdk-version>' + TI_MIN + '.GA</sdk-version>\n');
process.exit(1);
}
// check that hyperloop module was found in the tiapp.xml
var usingHyperloop = this.builder.tiapp.modules.some(function (m) {
return m.id === 'hyperloop' && (!m.platform || m.platform.indexOf('ios') !== -1 || m.platform.indexOf('iphone') !== -1);
});
if (!usingHyperloop) {
var pkg = require(path.join(__dirname, '..', 'package.json'));
this.logger.error('You cannot use the Hyperloop compiler without configuring the module.');
this.logger.error('Add the following to your tiapp.xml <modules> section:');
this.logger.error('');
this.logger.error(' <module version="' + pkg.version + '" platform="ios">hyperloop</module>\n');
process.exit(1);
}
if (!(this.builder.tiapp.properties && this.builder.tiapp.properties.hasOwnProperty('run-on-main-thread') && this.builder.tiapp.properties['run-on-main-thread'].value)) {
this.logger.error('You cannot use the Hyperloop compiler without configuring iOS to use main thread execution.');
this.logger.error('Add the following to your tiapp.xml <ti:app> section:');
this.logger.error('');
this.logger.error(' <property name="run-on-main-thread" type="bool">true</property>');
process.exit(1);
}
// check for min iOS version
if (this.appc.version.lt(this.builder.minIosVer, IOS_MIN)) {
this.logger.error('Hyperloop compiler works best with iOS ' + IOS_MIN + ' or greater.');
this.logger.error('Your setting is currently set to: ' + (this.builder.tiapp.ios['min-ios-ver'] || this.builder.minIosVer));
this.logger.error('You can change the version by adding the following to your');
this.logger.error('tiapp.xml <ios> section:');
this.logger.error('');
this.logger.error(' <min-ios-ver>' + IOS_MIN + '</min-ios-ver>\n');
process.exit(1);
}
var defaultXcodePath = path.join('/Applications', 'Xcode.app');
if (!fs.existsSync(defaultXcodePath)) {
this.logger.error('Hyperloop requires Xcode to be located at its default location under ' + defaultXcodePath);
this.logger.error('Please make sure to move Xcode to this location before continuing. For further information');
this.logger.error('on this issue check https://jira.appcelerator.org/browse/TIMOB-23956');
process.exit(1);
}
};
/**
* Sets up the build for the Hyperloop module.
* @param {Function} callback - A function to call when all setup tasks have completed.
*/
HyperloopiOSBuilder.prototype.setup = function setup() {
// create a temporary hyperloop directory
fs.ensureDirSync(this.hyperloopBuildDir);
};
/**
* Gets the system frameworks from the Hyperloop Metabase.
*/
HyperloopiOSBuilder.prototype.getSystemFrameworks = function getSystemFrameworks(callback) {
hm.metabase.getSystemFrameworks(this.hyperloopBuildDir, this.builder.xcodeTargetOS, this.builder.minIosVer, function (err, systemFrameworks) {
if (!err) {
this.systemFrameworks = new Map(systemFrameworks);
this.sdkInfo = this.systemFrameworks.get('$metadata');
this.systemFrameworks.delete('$metadata');
this.systemFrameworks.forEach(frameworkMetadata => {
this.frameworks.set(frameworkMetadata.name, frameworkMetadata);
}, this);
}
callback(err);
}.bind(this));
};
/**
* Has the Hyperloop Metabase generate the CocoaPods and then adds the symbols to the map of frameworks.
*/
HyperloopiOSBuilder.prototype.generateCocoaPods = function generateCocoaPods(callback) {
// attempt to handle CocoaPods for third-party frameworks
hm.metabase.generateCocoaPods(this.hyperloopBuildDir, this.builder, function (err, settings, modules) {
if (!err) {
this.hasCocoaPods = modules && modules.size > 0;
if (this.hasCocoaPods) {
this.cocoaPodsBuildSettings = settings || {};
modules.forEach(metadata => {
this.frameworks.set(metadata.name, metadata);
this.cocoaPodsProducts.push(metadata.name);
}, this);
}
}
callback(err);
}.bind(this));
};
/**
* Gets frameworks for any third-party dependencies defined in the Hyperloop config and compiles them.
*/
HyperloopiOSBuilder.prototype.processThirdPartyFrameworks = function processThirdPartyFrameworks(callback) {
var frameworks = this.frameworks;
var thirdPartyFrameworks = this.thirdPartyFrameworks;
var swiftSources = this.swiftSources;
var hyperloopBuildDir = this.hyperloopBuildDir;
var thirdparty = this.hyperloopConfig.ios.thirdparty || [];
var projectDir = this.builder.projectDir;
var xcodeAppDir = this.builder.xcodeAppDir;
var sdk = this.builder.xcodeTargetOS + this.builder.iosSdkVersion;
var builder = this.builder;
var logger = this.logger;
function arrayifyAndResolve(it) {
if (it) {
return (Array.isArray(it) ? it : [ it ]).map(function (name) {
return path.resolve(projectDir, name);
});
}
return null;
}
/**
* Processes any frameworks from modules or the app's platform/ios folder
*
* @param {Function} next Callback function
*/
function processFrameworks(next) {
if (!builder.frameworks || Object.keys(builder.frameworks).length === 0) {
return next();
}
// filter out native module libs
const filtered = {};
for (const name of Object.keys(builder.frameworks)) {
const framework = builder.frameworks[name];
const isNativeModule = builder.nativeLibModules.some(m => m.libFile === framework.path);
if (!isNativeModule) {
filtered[name] = framework;
}
}
hm.metabase.generateUserFrameworksMetadata(filtered, hyperloopBuildDir, function (err, modules) {
if (err) {
return next(err);
}
modules.forEach(moduleMetadata => {
thirdPartyFrameworks.set(moduleMetadata.name, moduleMetadata);
frameworks.set(moduleMetadata.name, moduleMetadata);
});
return next();
});
}
/**
* Processes third-party dependencies that are configured under the
* hyperloop.ios.thirdparty key
*
* These can be both uncompiled Swift and Objective-C source files as well as
* Frameworks.
*
* @param {Function} next Callback function
*/
function processConfiguredThirdPartySource(next) {
async.eachLimit(Object.keys(thirdparty), 5, function (frameworkName, next) {
var lib = thirdparty[frameworkName];
logger.debug('Generating includes for third-party source ' + frameworkName.green + ' (defined in appc.js)');
async.series([
function (cb) {
var headers = arrayifyAndResolve(lib.header);
if (headers) {
hm.metabase.generateUserSourceMappings(
hyperloopBuildDir,
headers,
function (err, includes) {
if (!err && includes && includes[frameworkName]) {
const metadata = new ModuleMetadata(frameworkName, headers[0], ModuleMetadata.MODULE_TYPE_STATIC);
metadata.typeMap = includes[frameworkName];
frameworks.set(metadata.name, metadata);
}
cb(err);
},
frameworkName
);
} else {
cb();
}
},
function (cb) {
var resources = arrayifyAndResolve(lib.resource);
if (resources) {
var extRegExp = /\.(xib|storyboard|m|mm|cpp|h|hpp|swift|xcdatamodel)$/;
async.eachLimit(resources, 5, function (dir, cb2) {
// compile the resources (.xib, .xcdatamodel, .xcdatamodeld,
// .xcmappingmodel, .xcassets, .storyboard)
hm.metabase.compileResources(dir, sdk, xcodeAppDir, false, function (err) {
if (!err) {
builder.copyDirSync(dir, xcodeAppDir, {
ignoreFiles: extRegExp
});
}
cb2(err);
});
}, cb);
} else {
cb();
}
},
function (cb) {
// generate metabase for swift files (if found)
var sources = arrayifyAndResolve(lib.source);
var swiftRegExp = /\.swift$/;
sources && sources.forEach(function (dir) {
fs.readdirSync(dir).forEach(function (filename) {
if (swiftRegExp.test(filename)) {
swiftSources.push({
framework: frameworkName,
source: path.join(dir, filename)
});
}
});
});
cb();
}
], next);
}, next);
}
async.series([
processFrameworks,
processConfiguredThirdPartySource
], callback);
};
/**
* Detects the configured swift version
*/
HyperloopiOSBuilder.prototype.detectSwiftVersion = function detectSwiftVersion(callback) {
var that = this;
exec('/usr/bin/xcrun swift -version', function (err, stdout) {
if (err) { return callback(err); }
var versionMatch = stdout.match(/version\s(\d.\d)/);
if (versionMatch !== null) {
that.swiftVersion = versionMatch[1];
}
callback();
});
};
/**
* Parses the given JS source for native framework usage.
* @param {Object} obj - JS object holding data about the file
* @param {String} obj.contents - current source code for the file
* @param {String} obj.original - original source of the file
* @param {String} sourceFilename - path to original JS file
* @param {String} destinationFilename - path to destination JS file
* @param {Function} cb - callback function
*/
HyperloopiOSBuilder.prototype.processJSFile = function processJSFile(obj, sourceFilename, destinationFilename, cb) {
const contents = obj.contents;
// skip empty content
if (!contents.length) {
return cb();
}
// look for any require which matches our hyperloop system frameworks
// parse the contents
// TODO: move all the HyperloopVisitor require/import manipulation into the parser call right here
// Otherwise we do two parser/ast-traversal/generation passes!
this.parserState = generator.parseFromBuffer(contents, sourceFilename, this.parserState || undefined);
// empty AST
if (!this.parserState) {
return cb();
}
const relPath = path.relative(this.resourcesDir, destinationFilename);
// get the result source code in case it was transformed and replace all system framework
// require() calls with the Hyperloop layer
const requireRegexp = /[\w_/\-\\.]+/ig;
const self = this;
const HyperloopVisitor = {
// ES5-style require calls
CallExpression: function (p) {
const theString = p.node.arguments[0];
let requireMatch;
if (p.get('callee').isIdentifier({ name: 'require' }) // Is this a require call?
&& theString && t.isStringLiteral(theString) // Is the 1st param a literal string?
&& (requireMatch = theString.value.match(requireRegexp)) !== null // Is it a hyperloop require?
) {
// hyperloop includes will always have a slash
const tok = requireMatch[0].split('/');
const pkg = tok[0];
// is it a normal js require or from alloy? do nothing...
if (pkg === 'alloy' || pkg.charAt(0) === '.' || pkg.charAt(0) === '/') {
return;
}
// if we use something like require("UIKit")
// that should require the helper such as require("UIKit/UIKit");
const className = tok[1] || pkg;
const framework = self.frameworks.get(pkg);
const include = framework && framework.typeMap[className];
const isBuiltin = pkg === 'Titanium';
self.logger.trace('Checking require for: ' + pkg.toLowerCase() + '/' + className.toLowerCase());
// if the framework is not found, then check if it was possibly misspelled
if (!framework && !isBuiltin) {
const pkgSoundEx = soundEx(pkg);
const maybes = Array.from(self.frameworks.keys()).filter(function (frameworkName) {
return soundEx(frameworkName) === pkgSoundEx;
});
if (maybes.length) {
self.logger.warn('The iOS framework "' + pkg + '" could not be found. Are you trying to use '
+ maybes.map(function (s) { return '"' + s + '"'; }).join(' or ') + ' instead? (' + relPath + ')');
}
// don't inject anything
return;
}
// remember any used frameworks
if (!isBuiltin) {
self.usedFrameworks.set(pkg, self.frameworks.get(pkg));
}
// if we haven't found it by now, then we try to help before failing
if (!include && className !== pkg && !isBuiltin) {
const classNameSoundEx = soundEx(className);
self.frameworks.forEach(frameworkMetadata => {
if (frameworkMetadata.typeMap[className]) {
throw new Error('Are you trying to use the iOS class "' + className + '" located in the framework "' + frameworkMetadata.name + '", not in "' + pkg + '"? (' + relPath + ')');
}
if (soundEx(frameworkMetadata.name) === classNameSoundEx) {
throw new Error('The iOS class "' + className + '" could not be found in the framework "' + pkg + '". Are you trying to use "' + frameworkMetadata.name + '" instead? (' + relPath + ')');
}
}, self);
throw new Error('The iOS class "' + className + '" could not be found in the framework "' + pkg + '". (' + relPath + ')');
}
const ref = 'hyperloop/' + pkg.toLowerCase() + '/' + className.toLowerCase();
self.references[ref] = 1;
if (include) {
// record our includes in which case we found a match
self.includes[include] = 1;
}
}
},
// ES6+-style imports
ImportDeclaration: function (p) {
const theString = p.node.source;
let requireMatch;
if (theString && t.isStringLiteral(theString) // module name is a string literal
&& (requireMatch = theString.value.match(requireRegexp)) !== null // Is it a hyperloop require?
) {
// hyperloop includes will always have a slash
const tok = requireMatch[0].split('/');
const pkg = tok[0];
// is it a normal js require or from alloy? do nothing...
if (pkg === 'alloy' || pkg.charAt(0) === '.' || pkg.charAt(0) === '/') {
return;
}
const isBuiltin = pkg === 'Titanium';
const framework = self.frameworks.get(pkg);
// if the framework is not found, then check if it was possibly misspelled
if (!framework && !isBuiltin) {
const pkgSoundEx = soundEx(pkg);
const maybes = Array.from(self.frameworks.keys()).filter(function (frameworkName) {
return soundEx(frameworkName) === pkgSoundEx;
});
if (maybes.length) {
self.logger.warn('The iOS framework "' + pkg + '" could not be found. Are you trying to use '
+ maybes.map(function (s) { return '"' + s + '"'; }).join(' or ') + ' instead? (' + relPath + ')');
}
// don't inject anything
return;
}
// remember any used frameworks
if (!isBuiltin) {
self.usedFrameworks.set(pkg, self.frameworks.get(pkg));
}
p.node.specifiers.forEach(function (spec) {
// import UIView from 'UIKit/UIView'; spec.imported is undefined and tok[1] holds className
// import { UIView } from 'UIKit'; spec.imported.name == 'UIView'
const className = (spec.imported ? spec.imported.name : tok[1]);
// What if they did:
// import UIView from 'UIKit'; ? className would be null here. Technically this is bad import anyways
// as it should be: import UIKit from 'UIKit/UIKit'; or import { UIView } from 'UIKit';
// FIXME: Should we bomb out with an error saying it's ambiguous import?
const include = framework && framework.typeMap[className];
self.logger.trace('Checking import for: ' + pkg.toLowerCase() + '/' + className.toLowerCase());
// if we haven't found it by now, then we try to help before failing
if (!include && className !== pkg && !isBuiltin) {
const classNameSoundEx = soundEx(className);
self.frameworks.forEach(frameworkMetadata => {
if (frameworkMetadata.typeMap[className]) {
throw new Error('Are you trying to use the iOS class "' + className + '" located in the framework "' + frameworkMetadata.name + '", not in "' + pkg + '"? (' + relPath + ')');
}
if (soundEx(frameworkMetadata.name) === classNameSoundEx) {
throw new Error('The iOS class "' + className + '" could not be found in the framework "' + pkg + '". Are you trying to use "' + frameworkMetadata.name + '" instead? (' + relPath + ')');
}
}, self);
throw new Error('The iOS class "' + className + '" could not be found in the framework "' + pkg + '". (' + relPath + ')');
}
const ref = 'hyperloop/' + pkg.toLowerCase() + '/' + className.toLowerCase();
self.references[ref] = 1;
if (include) {
// record our includes in which case we found a match
self.includes[include] = 1;
}
});
}
}
};
const ast = babelParser.parse(contents, { sourceFilename: sourceFilename, sourceType: 'unambiguous' });
traverse(ast, HyperloopVisitor);
cb();
};
/**
* Generates the metabase from the required Hyperloop files and then generate the source the source
* files from that metabase.
*/
HyperloopiOSBuilder.prototype.generateSourceFiles = function generateSourceFiles(callback) {
// no hyperloop files detected, we can stop here
if (!this.includes.length && !Object.keys(this.references).length) {
this.logger.info('Skipping ' + HL + ' compile, no usage found ...');
return callback(new StopHyperloopCompileError());
}
fs.ensureDirSync(this.hyperloopJSDir);
if (this.builder.forceCleanBuild || this.forceMetabase) {
this.logger.trace('Forcing a metabase rebuild');
} else {
this.logger.trace('Not necessarily forcing a metabase rebuild if already cached');
}
function generateMetabaseCallback(err, metabase, outfile, header, cached) {
if (err) {
return callback(err);
}
this.metabase = metabase;
this.metabase.classes = this.metabase.classes || {};
if (!cached) {
this.normalizeFrameworks(outfile);
this.determineFrameworkAvailability();
} else {
this.populateFrameworkAvailabilityFromCache();
}
if (cached && this.swiftSources.length === 0 && !this.forceMetabase) {
// if cached, skip generation
this.logger.info('Skipping ' + HL + ' compile, already generated...');
return callback();
}
// this has to be serial because each successful call to generateSwiftMetabase() returns a
// new metabase object that will be passed into the next file
async.eachSeries(this.swiftSources, function (entry, cb) {
this.logger.info('Generating metabase for swift ' + chalk.cyan(entry.framework + ' ' + entry.source));
hm.metabase.generateSwiftMetabase(
this.hyperloopBuildDir,
this.sdkInfo.sdkType,
this.sdkInfo.sdkPath,
this.sdkInfo.minVersion,
this.builder.xcodeTargetOS,
this.metabase,
entry.framework,
entry.source,
function (err, result, newMetabase) {
if (!err) {
this.metabase = newMetabase;
} else if (result) {
this.logger.error(result);
}
cb(err);
}.bind(this)
);
}.bind(this), callback);
}
var extraHeaderSearchPaths = [];
var extraFrameworkSearchPaths = [];
if (this.hasCocoaPods) {
var addSearchPathsFromCocoaPods = function (target, source) {
if (!source) {
return;
}
var cocoaPodsRoot = this.cocoaPodsBuildSettings.PODS_ROOT;
var cocoaPodsConfigurationBuildDir = path.join(this.builder.projectDir, 'build/iphone/build/Products', this.builder.xcodeTarget + '-' + this.builder.xcodeTargetOS);
var paths = source.split(' ');
paths.forEach(function (path) {
if (path === '$(inherited)') {
return;
}
var searchPath = path.replace('${PODS_ROOT}', cocoaPodsRoot);
searchPath = searchPath.replace(/\$(\{)?(PODS_CONFIGURATION_BUILD_DIR)(\})?/, cocoaPodsConfigurationBuildDir);
searchPath = searchPath.replace(/"/g, '');
target.push(searchPath);
});
}.bind(this);
addSearchPathsFromCocoaPods(extraHeaderSearchPaths, this.cocoaPodsBuildSettings.HEADER_SEARCH_PATHS);
addSearchPathsFromCocoaPods(extraFrameworkSearchPaths, this.cocoaPodsBuildSettings.FRAMEWORK_SEARCH_PATHS);
}
if (this.hyperloopConfig.ios.thirdparty) {
// Throw a deprecation warning regarding thirdparty-references in the appc.js
this.logger.warn('Defining third-party sources and frameworks in appc.js via the \'thirdparty\' section has been deprecated in Hyperloop 2.2.0 and will be removed in 5.0.0. The preferred way to provide third-party sources is either via dropping frameworks into the project\'s platform/ios folder or by using CocoaPods.');
this.headers = [];
Object.keys(this.hyperloopConfig.ios.thirdparty).forEach(function (frameworkName) {
var thirdPartyFrameworkConfig = this.hyperloopConfig.ios.thirdparty[frameworkName];
var headerPaths = Array.isArray(thirdPartyFrameworkConfig.header) ? thirdPartyFrameworkConfig.header : [ thirdPartyFrameworkConfig.header ];
headerPaths.forEach(function (headerPath) {
var searchPath = path.resolve(this.builder.projectDir, headerPath);
extraHeaderSearchPaths.push(searchPath);
extraFrameworkSearchPaths.push(searchPath);
this.headers.push(searchPath);
}, this);
}, this);
}
if (this.builder.frameworks) {
Object.keys(this.builder.frameworks).forEach(function (frameworkName) {
var frameworkInfo = this.builder.frameworks[frameworkName];
extraFrameworkSearchPaths.push(path.dirname(frameworkInfo.path));
}, this);
}
// Framework umbrella headers are required to properly resolve forward declarations
this.frameworks.forEach(frameworkMeta => {
if (!frameworkMeta.umbrellaHeader || !fs.existsSync(frameworkMeta.umbrellaHeader)) {
this.logger.warn(`Unable to detect framework umbrella header for ${frameworkMeta.name}.`);
}
this.includes[frameworkMeta.umbrellaHeader] = 1;
});
// generate the metabase from our includes
hm.metabase.generateMetabase(
this.hyperloopBuildDir,
this.sdkInfo.sdkType,
this.sdkInfo.sdkPath,
this.sdkInfo.minVersion,
Object.keys(this.includes),
false, // don't exclude system libraries
generateMetabaseCallback.bind(this),
this.builder.forceCleanBuild || this.forceMetabase,
extraHeaderSearchPaths,
extraFrameworkSearchPaths
);
};
/**
* Iterates over the metadata object and normalizes all framework properties.
*
* The metabase parser will leave the framework property as the path to the header
* file the symbol was found in if it is not contained in a .framework package.
*
* This normalization will try to associate the path with the actual framework
* name taken from our include map. Should the path be unknown we remove the
* framework property as it is a symbol which cannot be associated to a specific
* framework and we can't handle such symbols currently.
*
* @param {Object} metadata Metabdata object for a symbol (class, struct etc)
* @param {Object} fileToFrameworkMap Map with all known mappings of header files to their framework
*/
HyperloopiOSBuilder.prototype.normalizeFrameworks = function normalizeFrameworks(outfile) {
if (this.frameworks.size === 0) {
return;
}
var headerToFrameworkMap = {};
for (const metadata of this.frameworks.values()) {
var classes = Object.keys(metadata.typeMap);
for (var c = 0; c < classes.length; c++) {
var headerPathAndFilename = metadata.typeMap[classes[c]];
headerToFrameworkMap[headerPathAndFilename] = metadata.name;
}
}
function normalizeFrameworksInGroup(metadataGroup) {
if (!metadataGroup) {
return;
}
Object.keys(metadataGroup).forEach(function (entryName) {
var metadata = metadataGroup[entryName];
if (metadata.framework[0] !== '/') {
return;
}
if (headerToFrameworkMap[metadata.filename]) {
metadata.framework = headerToFrameworkMap[metadata.filename];
if (metadata.filename.indexOf('Pods/Headers/Public') === -1) {
// All files that do not come from CocoaPods are custom third-party
// sources configured in appc.js and need this property set to true
// to not generate an ObjC module wrapper.
metadata.customSource = true;
}
} else {
delete metadata.framework;
}
});
}
normalizeFrameworksInGroup(this.metabase.protocols);
normalizeFrameworksInGroup(this.metabase.classes);
normalizeFrameworksInGroup(this.metabase.structs);
normalizeFrameworksInGroup(this.metabase.functions);
normalizeFrameworksInGroup(this.metabase.vars);
normalizeFrameworksInGroup(this.metabase.enums);
normalizeFrameworksInGroup(this.metabase.typedefs);
if (this.metabase.blocks) {
Object.keys(this.metabase.blocks).forEach(function (entryName) {
if (entryName[0] === '/' && headerToFrameworkMap[entryName]) {
var normalizedFrameworkName = headerToFrameworkMap[entryName];
var frameworkBlocks = this.metabase.blocks[normalizedFrameworkName] || [];
frameworkBlocks = frameworkBlocks.concat(this.metabase.blocks[entryName].filter(function (block) {
return frameworkBlocks.every(function (existingBlock) {
return existingBlock.signature !== block.signature;
});
}));
this.metabase.blocks[normalizedFrameworkName] = frameworkBlocks;
delete this.metabase.blocks[entryName];
}
}, this);
}
fs.writeFileSync(outfile, JSON.stringify(this.metabase, null, 2));
};
/**
* Determines the general availability of a framework by iterating over the
* introducedIn property of all containing classes.
*
* The lowest version number found will be used as the introducedIn value for the
* framework. If no version information is available at all we set it to 0.0.0
* which means its available on all devices.
*/
HyperloopiOSBuilder.prototype.determineFrameworkAvailability = function determineFrameworkAvailability() {
const cacheData = {};
const unknownIntroducedIn = '100.0.0';
this.frameworks.forEach(metadata => {
let earliestIntroducedIn = unknownIntroducedIn;
Object.keys(metadata.typeMap).forEach(symbolName => {
const classMeta = this.metabase.classes[symbolName];
if (!classMeta || typeof classMeta.introducedIn !== 'string') {
return;
}
if (semver.lt(classMeta.introducedIn, earliestIntroducedIn)) {
earliestIntroducedIn = classMeta.introducedIn;
}
}, this);
metadata.introducedIn = earliestIntroducedIn !== unknownIntroducedIn ? earliestIntroducedIn : '0.0.0';
cacheData[metadata.name] = metadata.introducedIn;
}, this);
const cachePathAndFilename = path.join(this.hyperloopBuildDir, 'metadata-framework-availability.json');
fs.writeFileSync(cachePathAndFilename, JSON.stringify(cacheData));
};
/**
* Updates the framework map and sets all cached introducedIn values from cache.
*
* This only needs to be done in the main frameworks property since all other
* Maps reference the same metadata objects.
*/
HyperloopiOSBuilder.prototype.populateFrameworkAvailabilityFromCache = function populateFrameworkAvailabilityFromCache() {
const cachePathAndFilename = path.join(this.hyperloopBuildDir, 'metadata-framework-availability.json');
let availabilityMap = {};
try {
availabilityMap = JSON.parse(fs.readFileSync(cachePathAndFilename));
} catch (e) {
return this.determineFrameworkAvailability();
}
Object.keys(availabilityMap).forEach(frameworkName => {
this.frameworks.get(frameworkName).introducedIn = availabilityMap[frameworkName];
});
};
/**
* Generates the symbol reference based on the references from the metabase's parser state.
*/
HyperloopiOSBuilder.prototype.generateSymbolReference = function generateSymbolReference() {
if (!this.parserState) {
this.logger.info('Skipping ' + HL + ' generating of symbol references. Empty AST. ');
return;
}
var symbolRefFile = path.join(this.hyperloopBuildDir, 'symbol_references.json'),
json = JSON.stringify(this.parserState.getReferences(), null, 2);
if (!fs.existsSync(symbolRefFile) || fs.readFileSync(symbolRefFile).toString() !== json) {
this.forceStubGeneration = true;
this.logger.trace('Forcing regeneration of wrappers');
fs.writeFileSync(symbolRefFile, json);
} else {
this.logger.trace('Symbol references up-to-date');
}
};
/**
* Compiles the resources from the metabase.
*/
HyperloopiOSBuilder.prototype.compileResources = function compileResources(callback) {
var sdk = this.builder.xcodeTargetOS + this.builder.iosSdkVersion;
hm.metabase.compileResources(this.resourcesDir, sdk, this.builder.xcodeAppDir, false, callback);
};
/**
* Generates stubs from the metabase.
*/
HyperloopiOSBuilder.prototype.generateStubs = function generateStubs(callback) {
if (!this.parserState) {
this.logger.info('Skipping ' + HL + ' stub generation. Empty AST.');
return callback();
}
if (!this.forceStubGeneration) {
this.logger.debug('Skipping stub generation');
return callback();
}
// now generate the stubs
this.logger.debug('Generating stubs');
var started = Date.now();
generator.generateFromJSON(
this.builder.tiapp.name,
this.metabase,
this.parserState,
function (err, sourceSet, modules) {
if (err) {
return callback(err);
}
var codeGenerator = new generator.CodeGenerator(sourceSet, modules, this);
codeGenerator.generate(this.hyperloopJSDir);
var duration = Date.now() - started;
this.logger.info('Generation took ' + duration + ' ms');
callback();
}.bind(this),
this.frameworks
);
};
/**
* Copies Hyperloop generated JavaScript files into the app's `Resources/hyperloop` directory.
*/
HyperloopiOSBuilder.prototype.copyHyperloopJSFiles = function copyHyperloopJSFiles() {
// copy any native generated file references so that we can compile them
// as part of xcodebuild
var keys = Object.keys(this.references);
// only if we found references, otherwise, skip
if (!keys.length) {
return;
}
// check to see if we have any specific file native modules and copy them in
keys.forEach(function (ref) {
var file = path.join(this.hyperloopJSDir, ref.replace(/^hyperloop\//, '') + '.m');
if (fs.existsSync(file)) {
this.nativeModules[file] = 1;
}
}, this);
// check to see if we have any package modules and copy them in
this.usedFrameworks.forEach(frameworkMetadata => {
var file = path.join(this.hyperloopJSDir, frameworkMetadata.name.toLowerCase() + '/' + frameworkMetadata.name.toLowerCase() + '.m');
if (fs.existsSync(file)) {
this.nativeModules[file] = 1;
}
}, this);
var builder = this.builder,
logger = this.logger,
jsRegExp = /\.js$/;
(function scan(srcDir, destDir) {
fs.readdirSync(srcDir).forEach(function (name) {
var srcFile = path.join(srcDir, name),
srcStat = fs.statSync(srcFile);
if (srcStat.isDirectory()) {
return scan(srcFile, path.join(destDir, name));
}
if (!jsRegExp.test(name)) {
return;
}
var rel = path.relative(builder.projectDir, srcFile),
destFile = path.join(destDir, name),
destExists = fs.existsSync(destFile),
srcMtime = JSON.parse(JSON.stringify(srcStat.mtime)),
prev = builder.previousBuildManifest.files && builder.previousBuildManifest.files[rel],
contents = null,
hash = null,
changed = !destExists || !prev || prev.size !== srcStat.size || prev.mtime !== srcMtime || prev.hash !== (hash = builder.hash(contents = fs.readFileSync(srcFile).toString()));
builder.unmarkBuildDirFiles(destFile);
builder.currentBuildManifest.files[rel] = {
hash: contents === null && prev ? prev.hash : hash || builder.hash(contents || ''),
mtime: contents === null && prev ? prev.mtime : srcMtime,
size: contents === null && prev ? prev.size : srcStat.size
};
if (changed) {
logger.debug('Writing ' + chalk.cyan(destFile));
fs.ensureDirSync(destDir);
fs.writeFileSync(destFile, contents || fs.readFileSync(srcFile).toString());
} else {
logger.trace('No change, skipping ' + chalk.cyan(destFile));
}
});
}(this.hyperloopJSDir, this.hyperloopResourcesDir));
};