-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsetup
More file actions
executable file
·2110 lines (1817 loc) · 95.7 KB
/
setup
File metadata and controls
executable file
·2110 lines (1817 loc) · 95.7 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
#!/usr/bin/env node
import crypto from 'node:crypto';
import { execSync, spawn } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import * as url from 'node:url';
const __dirname = url.fileURLToPath(new URL('.', import.meta.url));
async function command(cmd, args, options) {
if (args == null) args = [];
if (options == null) options = {};
if (options.cwd == null) options.cwd = process.cwd();
if (process.platform == 'win32') {
options.shell = cmd.endsWith('.exe') ? false : true;
if (options.shell) {
args = [].concat(args);
for (let i = 0; i < args.length; i++) {
args[i] = '"' + args[i].replace(/"/g, '""') + '"';
}
}
}
console.log('\n> ' + cmd + ' ' + args.join(' '));
return new Promise((resolve, reject) => {
const child = spawn(cmd, args, {
stdio: 'inherit',
cwd: options.cwd,
env: process.env,
shell: options.shell
});
child.on('close', (code) => {
if (code !== 0) {
reject(new Error(`Child process exited with code ${code}`));
} else {
resolve(code);
}
});
child.on('error', (error) => {
reject(error);
});
});
}
function walkDirectory(dir, callback) {
// Get the contents of the directory
const entries = fs.readdirSync(dir);
// Iterate through each entry
for (const entry of entries) {
// Create full path
const fullPath = path.join(dir, entry);
// Get file/directory stats
const stats = fs.statSync(fullPath);
if (stats.isDirectory()) {
// Recursively walk through subdirectories
walkDirectory(fullPath, callback);
} else {
// Call the callback with the file path
callback(fullPath);
}
}
}
function extractCsNamespace(content) {
// Match 'namespace' followed by any valid C# namespace characters
// Handles optional whitespace and the opening brace
const namespaceMatch = content.match(/namespace\s+([\w.]+)\s*{/);
if (namespaceMatch) {
return namespaceMatch[1];
}
return null; // Return null if no namespace found
}
function getDotnetRid() {
const os = process.platform == 'darwin' ? 'osx'
: process.platform == 'win32' ? 'win'
: 'linux';
const arch = process.arch == 'arm64' ? 'arm64' : 'x64';
return os + '-' + arch;
}
function isLinuxArm64() {
try {
const arch = execSync('uname -m').toString().trim();
return arch == 'aarch64';
} catch (error) {
console.error('Error detecting architecture:', error);
return null;
}
}
async function downloadFile(fileUrl, destPath) {
const https = await import('node:https');
const http = await import('node:http');
return new Promise((resolve, reject) => {
const client = fileUrl.startsWith('https') ? https : http;
client.get(fileUrl, (response) => {
// Follow redirects (GitHub releases redirect to CDN)
if (response.statusCode >= 300 && response.statusCode < 400 && response.headers.location) {
downloadFile(response.headers.location, destPath).then(resolve).catch(reject);
response.resume();
return;
}
if (response.statusCode !== 200) {
response.resume();
reject(new Error('HTTP ' + response.statusCode + ' for ' + fileUrl));
return;
}
const file = fs.createWriteStream(destPath);
response.pipe(file);
file.on('finish', () => { file.close(resolve); });
file.on('error', (err) => { fs.unlinkSync(destPath); reject(err); });
}).on('error', reject);
});
}
async function extractArchive(archivePath, destDir) {
fs.mkdirSync(destDir, { recursive: true });
if (archivePath.endsWith('.tar.gz') || archivePath.endsWith('.tgz')) {
await command('tar', ['xzf', archivePath, '-C', destDir]);
} else if (archivePath.endsWith('.zip')) {
if (process.platform === 'win32') {
await command('powershell', [
'-Command',
'Expand-Archive -Path "' + archivePath + '" -DestinationPath "' + destDir + '" -Force'
]);
} else {
await command('unzip', ['-o', '-q', archivePath, '-d', destDir]);
}
}
}
// Example usage with async/await
async function main() {
process.chdir(__dirname);
let rawArgs = process.argv.slice(2);
var haxelib = process.platform == 'win32' ? 'haxelib.cmd' : './haxelib';
var haxe = process.platform == 'win32' ? 'haxe.cmd' : './haxe';
let haxeBuildArgs = [];
let buildCpp = rawArgs.indexOf('--cpp-cli') != -1 || rawArgs.indexOf('--cpp') != -1;
let buildCppLib = rawArgs.indexOf('--cpp-lib') != -1;
let buildCppLibTest = rawArgs.indexOf('--cpp-lib-test') != -1;
let buildCs = rawArgs.indexOf('--cs') != -1;
let buildCsDll = rawArgs.indexOf('--cs-dll') != -1;
let buildJs = rawArgs.indexOf('--js') != -1;
let buildPython = rawArgs.indexOf('--python') != -1 || rawArgs.indexOf('--py') != -1;
let buildLua = rawArgs.indexOf('--lua') != -1;
let buildJvm = rawArgs.indexOf('--jvm') != -1;
let buildIos = rawArgs.indexOf('--ios') != -1;
let buildAndroid = rawArgs.indexOf('--android') != -1;
let buildWasm = rawArgs.indexOf('--wasm') != -1;
let buildGodot = rawArgs.indexOf('--godot') != -1;
let buildGodotIos = rawArgs.indexOf('--godot-ios') != -1;
let buildGodotAndroid = rawArgs.indexOf('--godot-android') != -1;
let buildGodotWasm = rawArgs.indexOf('--godot-wasm') != -1;
let buildUnityPackage = rawArgs.indexOf('--unity-package') != -1;
let runTest = rawArgs.indexOf('--test') != -1;
let debug = false;
// --sample [web|unity|cpp|python|lua|sdl3|java] — copy built files into sample projects
let setupSample = rawArgs.indexOf('--sample') != -1;
let sampleTarget = null; // null = all, 'web', 'unity', 'cpp', 'python', 'lua', 'sdl3', or 'java'
if (setupSample) {
const idx = rawArgs.indexOf('--sample');
if (idx + 1 < rawArgs.length && !rawArgs[idx + 1].startsWith('-')) {
sampleTarget = rawArgs[idx + 1];
}
}
let i = 0;
while (i < rawArgs.length) {
if (rawArgs[i].startsWith('-D')) {
haxeBuildArgs.push('-D');
haxeBuildArgs.push(rawArgs[i].substring(2));
}
else if (rawArgs[i] == '--debug') {
debug = true;
haxeBuildArgs.push('--debug');
}
i++;
}
// Install dependencies (only needed for build targets, not --sample or --test)
if (buildCpp || buildCppLib || buildIos || buildAndroid || buildWasm || buildCs || buildJs || buildPython || buildLua || buildJvm) {
var haxelibRepoPath = path.join(__dirname, '.haxelib');
if (!fs.existsSync(haxelibRepoPath)) {
fs.mkdirSync(haxelibRepoPath);
}
await command(haxelib, ['dev', 'hxcpp', 'git/hxcpp', '--quiet'], { cwd: __dirname });
await command(haxelib, ['dev', 'hxcs', 'git/hxcs', '--quiet'], { cwd: __dirname });
await command(haxelib, ['dev', 'hscript', 'git/hscript', '--quiet'], { cwd: __dirname });
await command(haxelib, ['dev', 'yaml', 'git/yaml', '--quiet'], { cwd: __dirname });
if (buildJvm) {
await command(haxelib, ['dev', 'hxjava', 'git/hxjava', '--quiet'], { cwd: __dirname });
}
}
if (buildCpp) {
let haxeBuildCppArgs = [
'build-cli.hxml',
'--cpp', 'build/cpp',
'-D', 'HXCPP_DEBUG_LINK',
'-D', 'HXCPP_STACK_LINE',
'-D', 'HXCPP_STACK_TRACE',
'-D', 'HXCPP_CHECK_POINTER',
'-D', 'HXCPP_CPP11',
'-D', 'HXCPP_IMMORTAL_STATICS',
'-D', 'safeMode'
];
if (process.platform == 'darwin') {
console.log('Build loreline for mac');
await command(haxe, haxeBuildCppArgs.concat(haxeBuildArgs).concat([
'-D', 'mac', '-D', 'mac_arm64', '-D', 'no-compilation'
]));
await command('../../haxelib', ['run', 'hxcpp', 'Build.xml', '-DHXCPP_ARM64'].concat(debug ? ['-Ddebug'] : []), { cwd: path.join(__dirname, 'build', 'cpp') });
if (debug) {
fs.renameSync(path.join(__dirname, 'build/cpp/Cli-debug'), path.join(__dirname, 'build/cpp/loreline-arm64'));
}
else {
fs.renameSync(path.join(__dirname, 'build/cpp/Cli'), path.join(__dirname, 'build/cpp/loreline-arm64'));
}
await command(haxe, haxeBuildCppArgs.concat(haxeBuildArgs).concat([
'-D', 'mac', '-D', 'mac_x86_64', '-D', 'no-compilation'
]));
await command('../../haxelib', ['run', 'hxcpp', 'Build.xml', '-DHXCPP_M64', '-DHXCPP_X86_64'].concat(debug ? ['-Ddebug'] : []), { cwd: path.join(__dirname, 'build', 'cpp') });
if (debug) {
fs.renameSync(path.join(__dirname, 'build/cpp/Cli-debug'), path.join(__dirname, 'build/cpp/loreline-x86_64'));
}
else {
fs.renameSync(path.join(__dirname, 'build/cpp/Cli'), path.join(__dirname, 'build/cpp/loreline-x86_64'));
}
if (fs.existsSync(path.join(__dirname, 'loreline'))) {
fs.unlinkSync(path.join(__dirname, 'loreline'));
}
await command('lipo', [
'-create', 'loreline-arm64', 'loreline-x86_64',
'-output', '../../loreline'
], { cwd: path.join(__dirname, 'build', 'cpp') });
}
else if (process.platform == 'win32') {
console.log("Build loreline for windows");
await command(haxe, haxeBuildCppArgs.concat(haxeBuildArgs).concat([
'-D', 'windows', '-D', 'no-compilation'
]));
let haxelibCmd = fs.readFileSync(path.join(__dirname, 'haxelib.cmd'), 'utf8');
haxelibCmd = haxelibCmd.split('/git/').join('/../../git/');
fs.writeFileSync(path.join(__dirname, 'build', 'cpp', 'haxelib.cmd'), haxelibCmd);
await command(haxelib, ['run', 'hxcpp', 'Build.xml', '-DHXCPP_M64', '-DHXCPP_X86_64'].concat(debug ? ['-Ddebug'] : []), { cwd: path.join(__dirname, 'build', 'cpp') });
if (fs.existsSync(path.join(__dirname, 'loreline.exe'))) {
fs.unlinkSync(path.join(__dirname, 'loreline.exe'));
}
if (debug) {
fs.renameSync(path.join(__dirname, 'build/cpp/Cli-debug.exe'), path.join(__dirname, 'loreline.exe'));
}
else {
fs.renameSync(path.join(__dirname, 'build/cpp/Cli.exe'), path.join(__dirname, 'loreline.exe'));
}
}
else {
console.log("Build loreline for linux");
if (isLinuxArm64()) {
await command(haxe, haxeBuildCppArgs.concat(haxeBuildArgs).concat([
'-D', 'linux', '-D', 'no-compilation', '-D', 'linux_arm64'
]));
await command('../../haxelib', ['run', 'hxcpp', 'Build.xml', '-DHXCPP_ARM64'].concat(debug ? ['-Ddebug'] : []), { cwd: path.join(__dirname, 'build', 'cpp') });
}
else {
await command(haxe, haxeBuildCppArgs.concat(haxeBuildArgs).concat([
'-D', 'linux', '-D', 'no-compilation', '-D', 'linux_x86_64'
]));
await command('../../haxelib', ['run', 'hxcpp', 'Build.xml', '-DHXCPP_M64', '-DHXCPP_X86_64'].concat(debug ? ['-Ddebug'] : []), { cwd: path.join(__dirname, 'build', 'cpp') });
}
if (fs.existsSync(path.join(__dirname, 'loreline'))) {
fs.unlinkSync(path.join(__dirname, 'loreline'));
}
if (debug) {
fs.renameSync(path.join(__dirname, 'build/cpp/Cli-debug'), path.join(__dirname, 'loreline'));
}
else {
fs.renameSync(path.join(__dirname, 'build/cpp/Cli'), path.join(__dirname, 'loreline'));
}
}
}
if (buildCppLib) {
let haxeBuildCppLibArgs = [
'build-cpp-lib.hxml',
'-D', 'HXCPP_STACK_LINE',
'-D', 'HXCPP_STACK_TRACE'
];
if (process.platform == 'darwin') {
console.log('Build loreline C++ library for mac');
const buildDir = path.join(__dirname, 'build', 'cpp-lib', 'mac');
// Build arm64
await command(haxe, haxeBuildCppLibArgs.concat(haxeBuildArgs).concat([
'--cpp', 'build/cpp-lib/mac',
'-D', 'mac', '-D', 'mac_arm64'
]));
await command('../../../haxelib', ['run', 'hxcpp', 'Build.xml', '-DHXCPP_ARM64'].concat(debug ? ['-Ddebug'] : []), { cwd: buildDir });
// Rename intermediate static lib (hxcpp produces libLibrary.a on macOS)
const staticLib = debug ? 'libLibrary-debug.a' : 'libLibrary.a';
const armLib = path.join(buildDir, 'libLoreline-arm64.a');
fs.renameSync(path.join(buildDir, staticLib), armLib);
// Build x86_64
await command(haxe, haxeBuildCppLibArgs.concat(haxeBuildArgs).concat([
'--cpp', 'build/cpp-lib/mac',
'-D', 'mac', '-D', 'mac_x86_64'
]));
await command('../../../haxelib', ['run', 'hxcpp', 'Build.xml', '-DHXCPP_M64', '-DHXCPP_X86_64'].concat(debug ? ['-Ddebug'] : []), { cwd: buildDir });
const x64Lib = path.join(buildDir, 'libLoreline-x86_64.a');
fs.renameSync(path.join(buildDir, staticLib), x64Lib);
// Link arm64 dylib
const armDylib = path.join(buildDir, 'libLoreline-arm64.dylib');
await command('clang++', [
'-arch', 'arm64',
'-shared', '-fvisibility=hidden',
'-o', armDylib,
'-Wl,-force_load,' + armLib,
'-framework', 'Foundation', '-lpthread'
]);
await command('install_name_tool', ['-id', '@rpath/libLoreline.dylib', armDylib]);
// Link x86_64 dylib
const x64Dylib = path.join(buildDir, 'libLoreline-x86_64.dylib');
await command('clang++', [
'-arch', 'x86_64',
'-shared', '-fvisibility=hidden',
'-o', x64Dylib,
'-Wl,-force_load,' + x64Lib,
'-framework', 'Foundation', '-lpthread'
]);
await command('install_name_tool', ['-id', '@rpath/libLoreline.dylib', x64Dylib]);
// Create universal dylib
const outputDylib = path.join(buildDir, 'libLoreline.dylib');
if (fs.existsSync(outputDylib)) fs.unlinkSync(outputDylib);
await command('lipo', [
'-create', armDylib, x64Dylib,
'-output', outputDylib
]);
console.log('Built: ' + outputDylib);
}
else if (process.platform == 'win32') {
console.log('Build loreline C++ library for windows');
const buildDir = path.join(__dirname, 'build', 'cpp-lib', 'windows');
await command(haxe, haxeBuildCppLibArgs.concat(haxeBuildArgs).concat([
'--cpp', 'build/cpp-lib/windows',
'-D', 'windows'
]));
let haxelibCmd = fs.readFileSync(path.join(__dirname, 'haxelib.cmd'), 'utf8');
haxelibCmd = haxelibCmd.split('/git/').join('/../../../git/');
fs.writeFileSync(path.join(buildDir, 'haxelib.cmd'), haxelibCmd);
await command(haxelib, ['run', 'hxcpp', 'Build.xml', '-DHXCPP_M64', '-DHXCPP_X86_64'].concat(debug ? ['-Ddebug'] : []), { cwd: buildDir });
// On Windows, hxcpp with static_link produces a .lib; link into DLL via cl /LD
// Using cl instead of link directly ensures proper CRT DLL initialization
const staticLib = debug ? 'libLibrary-debug.lib' : 'libLibrary.lib';
const stubFile = path.join(buildDir, '_dll_stub.c');
fs.writeFileSync(stubFile, '/* stub for DLL creation */\n');
await command('cl', [
'/LD', '/MT',
stubFile,
'/Fe:' + path.join(buildDir, 'Loreline.dll'),
'/link',
'/WHOLEARCHIVE:' + path.join(buildDir, staticLib),
'ws2_32.lib', 'Crypt32.lib', 'user32.lib'
]);
console.log('Built: ' + path.join(buildDir, 'Loreline.dll'));
}
else {
console.log('Build loreline C++ library for linux');
const buildDir = path.join(__dirname, 'build', 'cpp-lib', 'linux');
if (isLinuxArm64()) {
await command(haxe, haxeBuildCppLibArgs.concat(haxeBuildArgs).concat([
'--cpp', 'build/cpp-lib/linux',
'-D', 'linux', '-D', 'linux_arm64'
]));
await command('../../../haxelib', ['run', 'hxcpp', 'Build.xml', '-DHXCPP_ARM64'].concat(debug ? ['-Ddebug'] : []), { cwd: buildDir });
}
else {
await command(haxe, haxeBuildCppLibArgs.concat(haxeBuildArgs).concat([
'--cpp', 'build/cpp-lib/linux',
'-D', 'linux', '-D', 'linux_x86_64'
]));
await command('../../../haxelib', ['run', 'hxcpp', 'Build.xml', '-DHXCPP_M64', '-DHXCPP_X86_64'].concat(debug ? ['-Ddebug'] : []), { cwd: buildDir });
}
// On Linux, hxcpp also produces libLibrary.a
const staticLib = debug ? 'libLibrary-debug.a' : 'libLibrary.a';
await command('g++', [
'-shared', '-fvisibility=hidden',
'-o', path.join(buildDir, 'libLoreline.so'),
'-Wl,--whole-archive', path.join(buildDir, staticLib), '-Wl,--no-whole-archive',
'-lpthread', '-ldl'
]);
console.log('Built: ' + path.join(buildDir, 'libLoreline.so'));
}
}
if (buildCppLibTest) {
console.log('Test loreline C++ library');
let buildDir;
if (process.platform == 'darwin') {
buildDir = path.join(__dirname, 'build', 'cpp-lib', 'mac');
await command('clang++', [
'-std=c++17',
'-o', path.join(buildDir, 'test_runner'),
'cpp/test/test_runner.cpp',
'-Icpp/include',
'-L' + buildDir,
'-lLoreline',
'-Wl,-rpath,@executable_path'
]);
}
else if (process.platform == 'win32') {
buildDir = path.join(__dirname, 'build', 'cpp-lib', 'windows');
await command('cl', [
'/std:c++17', '/EHsc',
'/I', 'cpp\\include',
'cpp\\test\\test_runner.cpp',
'/Fe:' + path.join(buildDir, 'test_runner.exe'),
'/link', '/LIBPATH:' + buildDir, 'Loreline.lib'
]);
}
else {
buildDir = path.join(__dirname, 'build', 'cpp-lib', 'linux');
await command('g++', [
'-std=c++17',
'-o', path.join(buildDir, 'test_runner'),
'cpp/test/test_runner.cpp',
'-Icpp/include',
'-L' + buildDir,
'-lLoreline',
"-Wl,-rpath,$ORIGIN"
]);
}
const testBin = path.join(buildDir, process.platform == 'win32' ? 'test_runner.exe' : 'test_runner');
await command(testBin, ['./test']);
}
if (buildIos) {
if (process.platform != 'darwin') {
throw new Error('iOS builds are only supported on macOS');
}
console.log('Build loreline .xcframework for iOS');
const iosBuildDir = path.join(__dirname, 'build', 'cpp-lib', 'ios');
const haxelibRelPath = '../../../haxelib';
let haxeBuildCppLibArgs = [
'build-cpp-lib.hxml',
'-D', 'HXCPP_STACK_LINE',
'-D', 'HXCPP_STACK_TRACE'
];
const iosLinkFrameworks = ['-framework', 'Foundation', '-framework', 'QuartzCore', '-lpthread'];
const iphoneosSDK = execSync('xcrun --sdk iphoneos --show-sdk-path').toString().trim();
const iphonesimSDK = execSync('xcrun --sdk iphonesimulator --show-sdk-path').toString().trim();
// hxcpp produces .a files with a suffix based on platform/arch:
// iphoneos + ARM64 → libLibrary.iphoneos-64.a
// iphonesim + M64 → libLibrary.iphonesim-64.a (both x86_64 and arm64)
const hxcppStaticLibName = (debug ? 'libLibrary-debug' : 'libLibrary');
// ── Device arm64 ──────────────────────────────────────────────
await command(haxe, haxeBuildCppLibArgs.concat(haxeBuildArgs).concat([
'--cpp', 'build/cpp-lib/ios',
'-D', 'iphoneos'
]));
await command(haxelibRelPath, ['run', 'hxcpp', 'Build.xml', '-DHXCPP_ARM64', '-Diphoneos'].concat(debug ? ['-Ddebug'] : []), { cwd: iosBuildDir });
const deviceStaticLib = hxcppStaticLibName + '.iphoneos-64.a';
const deviceDylib = path.join(iosBuildDir, 'libLoreline-device-arm64.dylib');
await command('xcrun', [
'--sdk', 'iphoneos', 'clang++',
'-arch', 'arm64',
'-shared', '-fvisibility=hidden',
'-isysroot', iphoneosSDK,
'-miphoneos-version-min=12.0',
'-o', deviceDylib,
'-Wl,-force_load,' + path.join(iosBuildDir, deviceStaticLib)
].concat(iosLinkFrameworks));
await command('install_name_tool', ['-id', '@rpath/Loreline.framework/Loreline', deviceDylib]);
// ── Simulator arm64 ──────────────────────────────────────────
await command(haxe, haxeBuildCppLibArgs.concat(haxeBuildArgs).concat([
'--cpp', 'build/cpp-lib/ios',
'-D', 'iphonesim', '-D', 'simulator'
]));
await command(haxelibRelPath, ['run', 'hxcpp', 'Build.xml', '-DHXCPP_ARM64', '-DHXCPP_M64', '-Diphonesim', '-Dsimulator'].concat(debug ? ['-Ddebug'] : []), { cwd: iosBuildDir });
// Rename the .a so it doesn't get overwritten by the x86_64 build
const simArm64StaticLib = 'libLoreline-sim-arm64.a';
fs.renameSync(
path.join(iosBuildDir, hxcppStaticLibName + '.iphonesim-arm64.a'),
path.join(iosBuildDir, simArm64StaticLib)
);
const simArm64Dylib = path.join(iosBuildDir, 'libLoreline-sim-arm64.dylib');
await command('xcrun', [
'--sdk', 'iphonesimulator', 'clang++',
'-arch', 'arm64',
'-shared', '-fvisibility=hidden',
'-isysroot', iphonesimSDK,
'-mios-simulator-version-min=12.0',
'-o', simArm64Dylib,
'-Wl,-force_load,' + path.join(iosBuildDir, simArm64StaticLib)
].concat(iosLinkFrameworks));
// ── Simulator x86_64 ─────────────────────────────────────────
await command(haxe, haxeBuildCppLibArgs.concat(haxeBuildArgs).concat([
'--cpp', 'build/cpp-lib/ios',
'-D', 'iphonesim', '-D', 'simulator'
]));
await command(haxelibRelPath, ['run', 'hxcpp', 'Build.xml', '-DHXCPP_M64', '-Diphonesim', '-Dsimulator'].concat(debug ? ['-Ddebug'] : []), { cwd: iosBuildDir });
const simX86StaticLib = hxcppStaticLibName + '.iphonesim-64.a';
const simX86Dylib = path.join(iosBuildDir, 'libLoreline-sim-x86_64.dylib');
await command('xcrun', [
'--sdk', 'iphonesimulator', 'clang++',
'-arch', 'x86_64',
'-shared', '-fvisibility=hidden',
'-isysroot', iphonesimSDK,
'-mios-simulator-version-min=12.0',
'-o', simX86Dylib,
'-Wl,-force_load,' + path.join(iosBuildDir, simX86StaticLib)
].concat(iosLinkFrameworks));
// Step 9: Create combined simulator dylib via lipo
const simCombinedDylib = path.join(iosBuildDir, 'libLoreline-sim.dylib');
if (fs.existsSync(simCombinedDylib)) fs.unlinkSync(simCombinedDylib);
await command('lipo', [
'-create', simArm64Dylib, simX86Dylib,
'-output', simCombinedDylib
]);
await command('install_name_tool', ['-id', '@rpath/Loreline.framework/Loreline', simCombinedDylib]);
// Step 10: Assemble .framework bundles
const deviceFrameworkDir = path.join(iosBuildDir, 'device', 'Loreline.framework');
const simFrameworkDir = path.join(iosBuildDir, 'simulator', 'Loreline.framework');
for (const fwDir of [deviceFrameworkDir, simFrameworkDir]) {
if (fs.existsSync(fwDir)) fs.rmSync(fwDir, { recursive: true, force: true });
fs.mkdirSync(path.join(fwDir, 'Headers'), { recursive: true });
fs.mkdirSync(path.join(fwDir, 'Modules'), { recursive: true });
// Copy header
fs.copyFileSync(
path.join(__dirname, 'cpp', 'include', 'Loreline.h'),
path.join(fwDir, 'Headers', 'Loreline.h')
);
// Copy module map and Info.plist from templates
fs.copyFileSync(
path.join(__dirname, 'tpl', 'ios', 'module.modulemap'),
path.join(fwDir, 'Modules', 'module.modulemap')
);
fs.copyFileSync(
path.join(__dirname, 'tpl', 'ios', 'Framework-Info.plist'),
path.join(fwDir, 'Info.plist')
);
}
// Copy the dylibs as the framework executables
fs.copyFileSync(deviceDylib, path.join(deviceFrameworkDir, 'Loreline'));
fs.copyFileSync(simCombinedDylib, path.join(simFrameworkDir, 'Loreline'));
// Step 11: Create .xcframework
const xcframeworkPath = path.join(iosBuildDir, 'Loreline.xcframework');
if (fs.existsSync(xcframeworkPath)) fs.rmSync(xcframeworkPath, { recursive: true, force: true });
await command('xcodebuild', [
'-create-xcframework',
'-framework', deviceFrameworkDir,
'-framework', simFrameworkDir,
'-output', xcframeworkPath
]);
console.log('Built: ' + xcframeworkPath);
// ── Static .xcframework with symbol renaming ─────────────────────
const llvmPrefix = execSync('brew --prefix llvm').toString().trim();
const llvmNm = path.join(llvmPrefix, 'bin', 'llvm-nm');
const llvmObjcopy = path.join(llvmPrefix, 'bin', 'llvm-objcopy');
if (!fs.existsSync(llvmNm) || !fs.existsSync(llvmObjcopy)) {
throw new Error(
'LLVM is required for static framework symbol renaming.\n' +
'Install it with: brew install llvm'
);
}
async function renameSymbols(staticLib, outputLib) {
const symbols = execSync(`${llvmNm} --defined-only -g ${staticLib}`, { maxBuffer: 64 * 1024 * 1024 })
.toString().split('\n');
const mappingFile = outputLib + '.symmap';
const mappings = [];
for (const line of symbols) {
const parts = line.trim().split(/\s+/);
if (parts.length < 3) continue;
const sym = parts[2];
// Keep only top-level Loreline_ symbols (public API)
// Namespaced loreline::* symbols (e.g. __ZN8loreline...) get renamed
const isPublicApi = /^__Z\d+Loreline_/.test(sym) ||
/^__ZN\d+Loreline_/.test(sym) ||
/^__ZT[INSV]+\d*Loreline_/.test(sym);
if (isPublicApi) continue;
if (sym.startsWith('_')) {
mappings.push(`${sym} _lorimpl_${sym.slice(1)}`);
}
}
fs.writeFileSync(mappingFile, mappings.join('\n'));
console.log(` Symbol renaming: ${mappings.length} renamed, ${symbols.length - mappings.length} kept`);
fs.copyFileSync(staticLib, outputLib);
await command(llvmObjcopy, ['--redefine-syms=' + mappingFile, outputLib]);
fs.unlinkSync(mappingFile);
}
// Rename symbols in each thin slice (llvm-objcopy cannot process fat binaries)
const deviceStaticRenamed = path.join(iosBuildDir, 'libLoreline-static-device-arm64.a');
await renameSymbols(path.join(iosBuildDir, deviceStaticLib), deviceStaticRenamed);
const simArm64StaticRenamed = path.join(iosBuildDir, 'libLoreline-static-sim-arm64.a');
await renameSymbols(path.join(iosBuildDir, simArm64StaticLib), simArm64StaticRenamed);
const simX86StaticRenamed = path.join(iosBuildDir, 'libLoreline-static-sim-x86_64.a');
await renameSymbols(path.join(iosBuildDir, simX86StaticLib), simX86StaticRenamed);
// Combine simulator slices
const simStaticCombined = path.join(iosBuildDir, 'libLoreline-static-sim.a');
if (fs.existsSync(simStaticCombined)) fs.unlinkSync(simStaticCombined);
await command('lipo', [
'-create', simArm64StaticRenamed, simX86StaticRenamed,
'-output', simStaticCombined
]);
// Assemble static .framework bundles
const deviceStaticFrameworkDir = path.join(iosBuildDir, 'device-static', 'Loreline.framework');
const simStaticFrameworkDir = path.join(iosBuildDir, 'simulator-static', 'Loreline.framework');
for (const fwDir of [deviceStaticFrameworkDir, simStaticFrameworkDir]) {
if (fs.existsSync(fwDir)) fs.rmSync(fwDir, { recursive: true, force: true });
fs.mkdirSync(path.join(fwDir, 'Headers'), { recursive: true });
fs.mkdirSync(path.join(fwDir, 'Modules'), { recursive: true });
fs.copyFileSync(
path.join(__dirname, 'cpp', 'include', 'Loreline.h'),
path.join(fwDir, 'Headers', 'Loreline.h')
);
fs.copyFileSync(
path.join(__dirname, 'tpl', 'ios', 'module.modulemap'),
path.join(fwDir, 'Modules', 'module.modulemap')
);
fs.copyFileSync(
path.join(__dirname, 'tpl', 'ios', 'Framework-Info.plist'),
path.join(fwDir, 'Info.plist')
);
}
fs.copyFileSync(deviceStaticRenamed, path.join(deviceStaticFrameworkDir, 'Loreline'));
fs.copyFileSync(simStaticCombined, path.join(simStaticFrameworkDir, 'Loreline'));
// Create static .xcframework
const staticXcframeworkPath = path.join(iosBuildDir, 'Loreline-static.xcframework');
if (fs.existsSync(staticXcframeworkPath)) fs.rmSync(staticXcframeworkPath, { recursive: true, force: true });
await command('xcodebuild', [
'-create-xcframework',
'-framework', deviceStaticFrameworkDir,
'-framework', simStaticFrameworkDir,
'-output', staticXcframeworkPath
]);
console.log('Built: ' + staticXcframeworkPath);
}
if (buildAndroid) {
console.log('Build loreline .aar for Android');
// Resolve Android NDK path
const ndkRoot = process.env.ANDROID_NDK_ROOT || process.env.ANDROID_NDK_HOME || process.env.ANDROID_NDK;
if (!ndkRoot) {
throw new Error('ANDROID_NDK_ROOT environment variable is not set. Set it to the path of your Android NDK installation.');
}
if (!fs.existsSync(ndkRoot)) {
throw new Error('Android NDK not found at: ' + ndkRoot);
}
const androidBuildDir = path.join(__dirname, 'build', 'cpp-lib', 'android');
const haxelibRelPath = '../../../haxelib';
// Determine host platform for NDK toolchain
let ndkHost;
if (process.platform == 'darwin') ndkHost = 'darwin-x86_64';
else if (process.platform == 'win32') ndkHost = 'windows-x86_64';
else ndkHost = 'linux-x86_64';
const ndkClang = path.join(ndkRoot, 'toolchains', 'llvm', 'prebuilt', ndkHost, 'bin', 'clang++');
const ndkStrip = path.join(ndkRoot, 'toolchains', 'llvm', 'prebuilt', ndkHost, 'bin', 'llvm-strip');
let haxeBuildCppLibArgs = [
'build-cpp-lib.hxml',
'-D', 'HXCPP_STACK_LINE',
'-D', 'HXCPP_STACK_TRACE'
];
// Step 1: Haxe -> C++ for Android
await command(haxe, haxeBuildCppLibArgs.concat(haxeBuildArgs).concat([
'--cpp', 'build/cpp-lib/android',
'-D', 'android',
'-D', 'ANDROID_NDK_ROOT=' + ndkRoot
]));
// Step 2: Compile and link for each ABI
const abiConfigs = [
{ abi: 'arm64-v8a', hxcppFlags: ['-DHXCPP_ARM64'], suffix: '-64', target: 'aarch64-linux-android21' },
{ abi: 'armeabi-v7a', hxcppFlags: ['-DHXCPP_ARMV7'], suffix: '-v7', target: 'armv7a-linux-androideabi21' },
{ abi: 'x86_64', hxcppFlags: ['-DHXCPP_M64', '-DHXCPP_X86_64'], suffix: '-x86_64', target: 'x86_64-linux-android21' },
{ abi: 'x86', hxcppFlags: ['-DHXCPP_M32', '-DHXCPP_X86'], suffix: '-x86', target: 'i686-linux-android21' }
];
for (const abi of abiConfigs) {
console.log(' Compiling for ' + abi.abi + '...');
// hxcpp compile
await command(haxelibRelPath, [
'run', 'hxcpp', 'Build.xml'
].concat(abi.hxcppFlags).concat(debug ? ['-Ddebug'] : []), { cwd: androidBuildDir });
const staticLibName = (debug ? 'libLibrary-debug' : 'libLibrary') + abi.suffix + '.a';
const staticLibPath = path.join(androidBuildDir, staticLibName);
if (!fs.existsSync(staticLibPath)) {
// Try without suffix (hxcpp naming can vary)
const altName = debug ? 'libLibrary-debug.a' : 'libLibrary.a';
const altPath = path.join(androidBuildDir, altName);
if (fs.existsSync(altPath)) {
fs.renameSync(altPath, staticLibPath);
} else {
throw new Error('Static library not found: ' + staticLibPath + ' (also tried ' + altPath + ')');
}
}
// Link .a into .so
const soDir = path.join(androidBuildDir, 'jni', abi.abi);
fs.mkdirSync(soDir, { recursive: true });
const soPath = path.join(soDir, 'libloreline.so');
await command(ndkClang, [
'--target=' + abi.target,
'-shared', '-fvisibility=hidden',
'-o', soPath,
'-Wl,--whole-archive', staticLibPath, '-Wl,--no-whole-archive',
'-llog'
]);
// Strip symbols for release
if (!debug) {
await command(ndkStrip, ['--strip-unneeded', soPath]);
}
console.log(' Built: ' + soPath);
}
// Step 3: Assemble the AAR
const aarDir = path.join(androidBuildDir, 'aar-staging');
if (fs.existsSync(aarDir)) fs.rmSync(aarDir, { recursive: true, force: true });
fs.mkdirSync(aarDir, { recursive: true });
// Copy AndroidManifest.xml
fs.copyFileSync(
path.join(__dirname, 'tpl', 'android', 'AndroidManifest.xml'),
path.join(aarDir, 'AndroidManifest.xml')
);
// The AAR format requires classes.jar to be present. Since Loreline is a
// pure native C++ library (no Java/Kotlin code), we create a valid but empty
// JAR. A JAR is a ZIP file, so we write the minimal 22-byte valid ZIP archive
// (just an End of Central Directory record with zero entries). A 0-byte file
// would not be a valid ZIP and would cause errors in Android build tools.
const emptyJarPath = path.join(aarDir, 'classes.jar');
const emptyZip = Buffer.from([
0x50, 0x4b, 0x05, 0x06, // End of central directory signature
0x00, 0x00, // Number of this disk
0x00, 0x00, // Disk where central directory starts
0x00, 0x00, // Number of central directory records on this disk
0x00, 0x00, // Total number of central directory records
0x00, 0x00, 0x00, 0x00, // Size of central directory
0x00, 0x00, 0x00, 0x00, // Offset of start of central directory
0x00, 0x00 // Comment length
]);
fs.writeFileSync(emptyJarPath, emptyZip);
// Copy jni/ directory with .so files
for (const abi of abiConfigs) {
const srcSo = path.join(androidBuildDir, 'jni', abi.abi, 'libloreline.so');
const dstDir = path.join(aarDir, 'jni', abi.abi);
fs.mkdirSync(dstDir, { recursive: true });
fs.copyFileSync(srcSo, path.join(dstDir, 'libloreline.so'));
}
// Copy prefab structure from template
const prefabSrcDir = path.join(__dirname, 'tpl', 'android', 'prefab');
const prefabDstDir = path.join(aarDir, 'prefab');
fs.cpSync(prefabSrcDir, prefabDstDir, { recursive: true });
// Copy header into prefab
const prefabIncludeDir = path.join(prefabDstDir, 'modules', 'loreline', 'include');
fs.mkdirSync(prefabIncludeDir, { recursive: true });
fs.copyFileSync(
path.join(__dirname, 'cpp', 'include', 'Loreline.h'),
path.join(prefabIncludeDir, 'Loreline.h')
);
// Copy .so files into prefab and update abi.json ndk version
let ndkVersion = 27; // default
try {
const sourceProps = fs.readFileSync(path.join(ndkRoot, 'source.properties'), 'utf8');
const versionMatch = sourceProps.match(/Pkg\.Revision\s*=\s*(\d+)/);
if (versionMatch) ndkVersion = parseInt(versionMatch[1], 10);
} catch (e) { /* use default */ }
for (const abi of abiConfigs) {
const prefabLibDir = path.join(prefabDstDir, 'modules', 'loreline', 'libs', 'android.' + abi.abi);
// Copy .so into prefab
fs.copyFileSync(
path.join(aarDir, 'jni', abi.abi, 'libloreline.so'),
path.join(prefabLibDir, 'libloreline.so')
);
// Update abi.json with actual NDK version
const abiJsonPath = path.join(prefabLibDir, 'abi.json');
const abiJson = JSON.parse(fs.readFileSync(abiJsonPath, 'utf8'));
abiJson.ndk = ndkVersion;
fs.writeFileSync(abiJsonPath, JSON.stringify(abiJson, null, ' ') + '\n');
}
// Step 4: Zip into .aar
const aarOutputPath = path.join(androidBuildDir, 'loreline.aar');
if (fs.existsSync(aarOutputPath)) fs.unlinkSync(aarOutputPath);
// Get list of entries in the aar staging directory
const aarEntries = fs.readdirSync(aarDir);
if (process.platform == 'win32') {
await command('powershell.exe', [
'-NoProfile', '-NonInteractive', '-Command',
`Compress-Archive -Path @(${aarEntries.map(e => "'" + e + "'").join(',')}) -DestinationPath '${aarOutputPath}' -Force`
], { cwd: aarDir });
} else {
await command('zip', ['-q', '-r', aarOutputPath].concat(aarEntries), { cwd: aarDir });
}
console.log('Built: ' + aarOutputPath);
}
if (buildWasm) {
console.log('Build loreline C++ library for WebAssembly (Emscripten)');
const emsdkRoot = process.env.EMSDK;
if (!emsdkRoot) {
throw new Error('EMSDK environment variable is not set. Install Emscripten SDK and set EMSDK.');
}
const wasmNothreadsBuildDir = path.join(__dirname, 'build', 'cpp-lib', 'wasm-nothreads');
const wasmThreadsBuildDir = path.join(__dirname, 'build', 'cpp-lib', 'wasm-threads');
const wasmOutputDir = path.join(__dirname, 'build', 'cpp-lib', 'wasm');
let haxeBuildCppLibArgs = [
'build-cpp-lib.hxml',
'-D', 'HXCPP_STACK_LINE',
'-D', 'HXCPP_STACK_TRACE'
];
// Step 1: Haxe → C++ (once, with emscripten define)
await command(haxe, haxeBuildCppLibArgs.concat(haxeBuildArgs).concat([
'--cpp', 'build/cpp-lib/wasm-nothreads',
'-D', 'emscripten'
]));
// Copy generated C++ to threads build dir
if (fs.existsSync(wasmThreadsBuildDir)) fs.rmSync(wasmThreadsBuildDir, { recursive: true, force: true });
fs.cpSync(wasmNothreadsBuildDir, wasmThreadsBuildDir, { recursive: true });
// Step 2: Build nothreads variant
console.log(' Building nothreads variant...');
await command('../../../haxelib', [
'run', 'hxcpp', 'Build.xml',
'-Demscripten',
'-DHXCPP_EMSCRIPTEN_FPIC'
].concat(debug ? ['-Ddebug'] : []), { cwd: wasmNothreadsBuildDir });
// Step 3: Build threads variant
console.log(' Building threads variant...');
await command('../../../haxelib', [
'run', 'hxcpp', 'Build.xml',
'-Demscripten',
'-DHXCPP_MULTI_THREADED_APP',
'-DHXCPP_MULTI_THREADED',
'-DHXCPP_EMSCRIPTEN_FPIC'
].concat(debug ? ['-Ddebug'] : []), { cwd: wasmThreadsBuildDir });
// Step 4: Copy final .a files to wasm/
const staticLibName = debug ? 'libLibrary-debug.a' : 'libLibrary.a';
fs.mkdirSync(wasmOutputDir, { recursive: true });
fs.copyFileSync(
path.join(wasmNothreadsBuildDir, staticLibName),
path.join(wasmOutputDir, 'libLoreline.nothreads.a')
);
fs.copyFileSync(
path.join(wasmThreadsBuildDir, staticLibName),
path.join(wasmOutputDir, 'libLoreline.threads.a')
);
console.log('Built: ' + path.join(wasmOutputDir, 'libLoreline.nothreads.a'));
console.log('Built: ' + path.join(wasmOutputDir, 'libLoreline.threads.a'));
}
if (buildGodot || buildGodotIos || buildGodotAndroid || buildGodotWasm) {
const godotDir = path.join(__dirname, 'godot');
const sconsTarget = debug ? 'template_debug' : 'template_release';
// --godot: build for host platform (macOS/Windows/Linux)
if (buildGodot) {
console.log('Build loreline GDExtension for Godot');
// Determine platform and architecture for scons
let sconsPlatform;
let sconsArchList;
if (process.platform == 'darwin') {
sconsPlatform = 'macos';
sconsArchList = ['arm64', 'x86_64'];
} else if (process.platform == 'win32') {
sconsPlatform = 'windows';
sconsArchList = ['x86_64'];
} else {
sconsPlatform = 'linux';
sconsArchList = [isLinuxArm64() ? 'arm64' : 'x86_64'];
}
for (const sconsArch of sconsArchList) {
let sconsArgs = [
'platform=' + sconsPlatform,
'arch=' + sconsArch,
'target=' + sconsTarget
];
await command('scons', sconsArgs, { cwd: godotDir });
console.log('Built: GDExtension for ' + sconsPlatform + ' (' + sconsArch + ')');
}
// On macOS, create universal binary via lipo
if (sconsPlatform == 'macos' && sconsArchList.length > 1) {
const arm64Lib = path.join(godotDir, 'bin', 'libloreline_godot.arm64.dylib');