forked from PenguinMod/PenguinMod-Packager
-
Notifications
You must be signed in to change notification settings - Fork 1
/
packager.js
1680 lines (1520 loc) · 60.3 KB
/
packager.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
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
import {EventTarget, CustomEvent} from '../common/event-target';
import sha256 from './sha256';
import escapeXML from '../common/escape-xml';
import largeAssets from './large-assets';
import request from '../common/request';
import pngToAppleICNS from './icns';
import {buildId, verifyBuildId} from './build-id';
import {encode, decode} from './base85';
import {parsePlist, generatePlist} from './plist';
import {APP_NAME, WEBSITE, COPYRIGHT_NOTICE, ACCENT_COLOR} from './brand';
import {OutdatedPackagerError} from '../common/errors';
import {darken} from './colors';
import {Adapter} from './adapter';
const PROGRESS_LOADED_SCRIPTS = 0.1;
// Used by environments that fetch the entire compressed project before calling loadProject()
const PROGRESS_FETCHED_COMPRESSED = 0.75;
const PROGRESS_EXTRACTED_COMPRESSED = 0.98;
// Used by environments that pass a project.json into loadProject() and fetch assets separately
const PROGRESS_FETCHED_PROJECT_JSON = 0.2;
const PROGRESS_FETCHED_ASSETS = 0.98;
const removeUnnecessaryEmptyLines = (string) => string.split('\n')
.filter((line, index, array) => {
if (index === 0 || index === array.length - 1) return true;
if (line.trim().length === 0 && array[index - 1].trim().length === 0) return false;
return true;
})
.join('\n');
export const getJSZip = async () => (await import(/* webpackChunkName: "jszip" */ 'jszip')).default;
const setFileFast = (zip, path, data) => {
zip.files[path] = data;
};
const interpolate = (a, b, t) => a + t * (b - a);
const SELF_LICENSE = {
title: APP_NAME,
homepage: WEBSITE,
license: COPYRIGHT_NOTICE
};
const SCRATCH_LICENSE = {
title: 'Scratch',
homepage: 'https://scratch.mit.edu/',
license: `Copyright (c) 2016, Massachusetts Institute of Technology
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.`
};
const ELECTRON_LICENSE = {
title: 'Electron',
homepage: 'https://www.electronjs.org/',
license: `Copyright (c) Electron contributors
Copyright (c) 2013-2020 GitHub Inc.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.`
};
const COPYRIGHT_HEADER = `/*!
Parts of this script are from the ${APP_NAME} <${WEBSITE}>, licensed as follows:
${SELF_LICENSE.license}
Parts of this script are from Scratch <https://scratch.mit.edu/>, licensed as follows:
${SCRATCH_LICENSE.license}
*/\n`;
const generateChromiumLicenseHTML = (licenses) => {
const style = `<style>body { font-family: sans-serif; }</style>`;
const pretext = `<h2>The following entries were added by the ${APP_NAME}</h2>`;
const convertedLicenses = licenses.map((({title, license, homepage}, index) => `
<div class="product">
<span class="title">${escapeXML(title)}</span>
<span class="homepage"><a href="${escapeXML(homepage)}">homepage</a></span>
<input type="checkbox" hidden id="p4-${index}">
<label class="show" for="p4-${index}" tabindex="0"></label>
<div class="licence">
<pre>${escapeXML(license)}</pre>
</div>
</div>
`));
return `${style}${pretext}${convertedLicenses.join('\n')}`;
};
// Unique identifier for the app. If this changes, things like local cloud variables will be lost.
// This should be in reverse-DNS format.
// https://developer.apple.com/documentation/bundleresources/information_property_list/cfbundleidentifier
const CFBundleIdentifier = 'CFBundleIdentifier';
// Even if you fork the packager, you shouldn't change this string unless you want packaged macOS apps
// to lose all their data.
const bundleIdentifierPrefix = 'org.turbowarp.packager.userland.';
// CFBundleName is displayed in the menu bar.
// I'm not actually sure where CFBundleDisplayName is displayed.
// Documentation says that CFBundleName is only supposed to be 15 characters and that CFBundleDisplayName
// should be used for longer names, but in reality CFBundleName seems to not have a length limit.
// https://developer.apple.com/documentation/bundleresources/information_property_list/cfbundlename
// https://developer.apple.com/documentation/bundleresources/information_property_list/cfbundledisplayname
const CFBundleName = 'CFBundleName';
const CFBundleDisplayName = 'CFBundleDisplayName';
// The name of the executable in the .app/Contents/MacOS folder
// https://developer.apple.com/documentation/bundleresources/information_property_list/cfbundleexecutable
const CFBundleExecutable = 'CFBundleExecutable';
// macOS's "About" screen will display: "Version {CFBundleShortVersionString} ({CFBundleVersion})"
// Apple's own apps are inconsistent about what they display here. Some apps set both of these to the same thing
// so you see eg. "Version 15.0 (15.0)" while others set CFBundleShortVersionString to a semver-like and
// treat CFBundleVersion as a simple build number eg. "Version 1.4.0 (876)"
// Apple's documentation says both of these are supposed to be major.minor.patch, but in reality it doesn't
// even have to contain numbers and everything seems to work fine.
// https://developer.apple.com/documentation/bundleresources/information_property_list/cfbundleversion
// https://developer.apple.com/documentation/bundleresources/information_property_list/cfbundleshortversionstring
const CFBundleVersion = 'CFBundleVersion';
const CFBundleShortVersionString = 'CFBundleShortVersionString';
// Describes the category of the app
// https://developer.apple.com/documentation/bundleresources/information_property_list/lsapplicationcategorytype
const LSApplicationCategoryType = 'LSApplicationCategoryType';
const generateMacReadme = (options) => `When you try to double click on the app to run it, you will probably see this warning:
"${options.app.packageName} cannot be opened because the developer cannot be verified."
This is normal. Press cancel.
To run the app:
1) Control+click on the app file (${options.app.packageName} in the same folder as this document) and select "Open".
2) If a warning appears, select "Open" if it's an option.
3) If a warning appears but "Open" isn't an option, press "Cancel" and repeat from step 1.
The open button will appear the second time the warning appears.
After completing these steps, the app should run without any further warnings.
Feel free to drag the app into your Applications folder.
`;
/**
* @param {string} packageName
*/
const validatePackageName = (packageName) => {
// Characters considered unsafe filenames on Windows
const BLOCKLIST = ['/', '\\', ':', '*', '?', '<', '>', '|'];
if (BLOCKLIST.some((i) => packageName.includes(i))) {
throw new Error(`Invalid package name: ${packageName}. It must not use the characters: ${BLOCKLIST.join(' ')}`)
}
};
class Packager extends EventTarget {
constructor () {
super();
this.project = null;
this.options = Packager.DEFAULT_OPTIONS();
this.aborted = false;
this.used = false;
}
abort () {
if (!this.aborted) {
this.aborted = true;
this.dispatchEvent(new Event('abort'));
}
}
ensureNotAborted () {
if (this.aborted) {
throw new Error('Aborted');
}
}
async fetchLargeAsset (name, type) {
this.ensureNotAborted();
const asset = largeAssets[name];
if (!asset) {
throw new Error(`Invalid asset: ${name}`);
}
if (typeof __ASSETS__ !== 'undefined' && __ASSETS__[asset.src]) {
return __ASSETS__[asset.src];
}
const dispatchProgress = (progress) => this.dispatchEvent(new CustomEvent('large-asset-fetch', {
detail: {
asset: name,
progress
}
}));
dispatchProgress(0);
let result;
let cameFromCache = false;
try {
const cached = await Adapter.getCachedAsset(asset);
if (cached) {
result = cached;
cameFromCache = true;
dispatchProgress(0.5);
}
} catch (e) {
console.warn(e);
}
if (!result) {
let url = asset.src;
if (asset.useBuildId) {
url += `?${buildId}`;
}
result = await request({
url,
type,
estimatedSize: asset.estimatedSize,
progressCallback: (progress) => {
dispatchProgress(progress);
},
abortTarget: this
});
}
if (asset.useBuildId && !verifyBuildId(buildId, result)) {
throw new OutdatedPackagerError('Build ID does not match.');
}
if (asset.sha256) {
const hash = await sha256(result);
if (hash !== asset.sha256) {
throw new Error(`Hash mismatch for ${name}, found ${hash} but expected ${asset.sha256}`);
}
}
if (!cameFromCache) {
try {
await Adapter.cacheAsset(asset, result);
} catch (e) {
console.warn(e);
}
}
dispatchProgress(1);
return result;
}
getAddonOptions () {
return {
...this.options.chunks,
specialCloudBehaviors: this.options.cloudVariables.specialCloudBehaviors,
unsafeCloudBehaviors: this.options.cloudVariables.unsafeCloudBehaviors,
pause: this.options.controls.pause.enabled
};
}
async loadResources () {
const texts = [COPYRIGHT_HEADER];
if (this.project.analysis.usesMusic) {
texts.push(await this.fetchLargeAsset('scaffolding', 'text'));
} else {
texts.push(await this.fetchLargeAsset('scaffolding-min', 'text'));
}
if (Object.values(this.getAddonOptions()).some((i) => i)) {
texts.push(await this.fetchLargeAsset('addons', 'text'));
}
this.script = texts.join('\n').replace(/<\/script>/g,"</scri'+'pt>");
}
computeWindowSize () {
let width = this.options.stageWidth;
let height = this.options.stageHeight;
if (
this.options.controls.greenFlag.enabled ||
this.options.controls.stopAll.enabled ||
this.options.controls.pause.enabled
) {
height += 48;
}
return {width, height};
}
getPlistPropertiesForPrimaryExecutable () {
return {
[CFBundleIdentifier]: `${bundleIdentifierPrefix}${this.options.app.packageName}`,
// For simplicity, we'll set these to the same thing
[CFBundleName]: this.options.app.windowTitle,
[CFBundleDisplayName]: this.options.app.windowTitle,
// We do rename the executable
[CFBundleExecutable]: this.options.app.packageName,
// For simplicity, we'll set these to the same thing
[CFBundleVersion]: this.options.app.version,
[CFBundleShortVersionString]: this.options.app.version,
// Most items generated by the packager are games
[LSApplicationCategoryType]: 'public.app-category.games'
};
}
async updatePlist (zip, name, newProperties) {
const contents = await zip.file(name).async('string');
const plist = parsePlist(contents);
Object.assign(plist, newProperties);
zip.file(name, generatePlist(plist));
}
async addNwJS (projectZip) {
const packageName = this.options.app.packageName;
validatePackageName(packageName);
const nwjsBuffer = await this.fetchLargeAsset(this.options.target, 'arraybuffer');
const nwjsZip = await (await getJSZip()).loadAsync(nwjsBuffer);
const isWindows = this.options.target.startsWith('nwjs-win');
const isMac = this.options.target === 'nwjs-mac';
const isLinux = this.options.target.startsWith('nwjs-linux');
// NW.js Windows folder structure:
// * (root)
// +-- nwjs-v0.49.0-win-x64
// +-- nw.exe (executable)
// +-- credits.html
// +-- (project data)
// +-- ...
// NW.js macOS folder structure:
// * (root)
// +-- nwjs-v0.49.0-osx-64
// +-- credits.html
// +-- nwjs.app
// +-- Contents
// +-- Resources
// +-- app.icns (icon)
// +-- app.nw
// +-- (project data)
// +-- MacOS
// +-- nwjs (executable)
// +-- ...
// the first folder, something like "nwjs-v0.49.0-win-64"
const nwjsPrefix = Object.keys(nwjsZip.files)[0].split('/')[0];
const zip = new (await getJSZip());
// Copy NW.js files to the right place
for (const path of Object.keys(nwjsZip.files)) {
const file = nwjsZip.files[path];
let newPath = path.replace(nwjsPrefix, packageName);
if (isWindows) {
newPath = newPath.replace('nw.exe', `${packageName}.exe`);
} else if (isMac) {
newPath = newPath.replace('nwjs.app', `${packageName}.app`);
} else if (isLinux) {
newPath = newPath.replace(/nw$/, packageName);
}
setFileFast(zip, newPath, file);
}
const ICON_NAME = 'icon.png';
const icon = await Adapter.getAppIcon(this.options.app.icon);
const manifest = {
name: packageName,
main: 'main.js',
version: this.options.app.version,
window: {
width: this.computeWindowSize().width,
height: this.computeWindowSize().height,
icon: ICON_NAME
}
};
let dataPrefix;
if (isWindows) {
dataPrefix = `${packageName}/`;
} else if (isMac) {
zip.file(`${packageName}/How to run ${packageName}.txt`, generateMacReadme(this.options));
const icnsData = await pngToAppleICNS(icon);
zip.file(`${packageName}/${packageName}.app/Contents/Resources/app.icns`, icnsData);
dataPrefix = `${packageName}/${packageName}.app/Contents/Resources/app.nw/`;
} else if (isLinux) {
const startScript = `#!/bin/bash
cd "$(dirname "$0")"
./${packageName}`;
zip.file(`${packageName}/start.sh`, startScript, {
unixPermissions: 0o100755
});
dataPrefix = `${packageName}/`;
}
// Copy project files and extra NW.js files to the right place
for (const path of Object.keys(projectZip.files)) {
setFileFast(zip, dataPrefix + path, projectZip.files[path]);
}
zip.file(dataPrefix + ICON_NAME, icon);
zip.file(dataPrefix + 'package.json', JSON.stringify(manifest, null, 4));
zip.file(dataPrefix + 'main.js', `
const start = () => nw.Window.open('index.html', {
position: 'center',
new_instance: true
});
nw.App.on('open', start);
start();`);
const creditsHtmlPath = `${packageName}/credits.html`;
const creditsHtml = await zip.file(creditsHtmlPath).async('string');
zip.file(creditsHtmlPath, creditsHtml + generateChromiumLicenseHTML([
SELF_LICENSE,
SCRATCH_LICENSE
]));
return zip;
}
async addElectron (projectZip) {
const packageName = this.options.app.packageName;
validatePackageName(packageName);
const buffer = await this.fetchLargeAsset(this.options.target, 'arraybuffer');
const electronZip = await (await getJSZip()).loadAsync(buffer);
const isWindows = this.options.target.includes('win');
const isMac = this.options.target.includes('mac');
const isLinux = this.options.target.includes('linux');
// See https://www.electronjs.org/docs/latest/tutorial/application-distribution#manual-distribution
// Electron Windows/Linux folder structure:
// * (root)
// +-- electron.exe (executable)
// +-- resources
// +-- default_app.asar (we will delete this)
// +-- app (we will create this)
// +-- index.html and the other project files (we will create this)
// +-- LICENSES.chromium.html and everything else
// Electron macOS folder structure:
// * (root)
// +-- Electron.app
// +-- Contents
// +-- Info.plist (we must update)
// +-- MacOS
// +-- Electron (executable)
// +-- Frameworks
// +-- Electron Helper.app
// +-- Contents
// +-- Info.plist (we must update)
// +-- Electron Helper (GPU).app
// +-- Contents
// +-- Info.plist (we must update)
// +-- Electron Helper (Renderer).app
// +-- Contents
// +-- Info.plist (we must update)
// +-- Electron Helper (Plugin).app
// +-- Contents
// +-- Info.plist (we must update)
// +-- and several other helpers which we won't touch
// +-- Resources
// +-- default_app.asar (we will delete this)
// +-- electron.icns (we will update this)
// +-- app (we will create this)
// +-- index.html and the other project files (we will create this)
// +-- LICENSES.chromium.html and other license files
const zip = new (await getJSZip());
for (const path of Object.keys(electronZip.files)) {
const file = electronZip.files[path];
// On Windows and Linux, make an inner folder inside the zip. Zip extraction tools will sometimes make
// a mess if you don't make an inner folder.
// On macOS, the .app is already itself a folder already and macOS will always make a folder for the
// extracted files if there's multiple files at the root.
let newPath;
if (isMac) {
newPath = path;
} else {
newPath = `${packageName}/${path}`;
}
if (isWindows) {
newPath = newPath.replace('electron.exe', `${packageName}.exe`);
} else if (isMac) {
newPath = newPath.replace('Electron.app', `${packageName}.app`);
newPath = newPath.replace(/Electron$/, packageName);
} else if (isLinux) {
newPath = newPath.replace(/electron$/, packageName);
}
setFileFast(zip, newPath, file);
}
const rootPrefix = isMac ? '' : `${packageName}/`;
const creditsHtml = await zip.file(`${rootPrefix}LICENSES.chromium.html`).async('string');
zip.file(`${rootPrefix}licenses.html`, creditsHtml + generateChromiumLicenseHTML([
SELF_LICENSE,
SCRATCH_LICENSE,
ELECTRON_LICENSE
]));
zip.remove(`${rootPrefix}LICENSE.txt`);
zip.remove(`${rootPrefix}LICENSES.chromium.html`);
zip.remove(`${rootPrefix}LICENSE`);
zip.remove(`${rootPrefix}version`);
zip.remove(`${rootPrefix}resources/default_app.asar`);
const contentsPrefix = isMac ? `${rootPrefix}${packageName}.app/Contents/` : rootPrefix;
const resourcesPrefix = isMac ? `${contentsPrefix}Resources/app/` : `${contentsPrefix}resources/app/`;
const electronMainName = 'electron-main.js';
const iconName = 'icon.png';
const icon = await Adapter.getAppIcon(this.options.app.icon);
zip.file(`${resourcesPrefix}${iconName}`, icon);
const manifest = {
name: packageName,
main: electronMainName,
version: this.options.app.version
};
zip.file(`${resourcesPrefix}package.json`, JSON.stringify(manifest, null, 4));
const mainJS = `'use strict';
const {app, BrowserWindow, Menu, shell, screen, dialog} = require('electron');
const path = require('path');
const isWindows = process.platform === 'win32';
const isMac = process.platform === 'darwin';
const isLinux = process.platform === 'linux';
if (isMac) {
Menu.setApplicationMenu(Menu.buildFromTemplate([
{ role: 'appMenu' },
{ role: 'fileMenu' },
{ role: 'editMenu' },
{ role: 'windowMenu' },
{ role: 'help' }
]));
} else {
Menu.setApplicationMenu(null);
}
const resourcesURL = Object.assign(new URL('file://'), {
pathname: path.join(__dirname, '/')
}).href;
const defaultProjectURL = new URL('./index.html', resourcesURL).href;
const createWindow = (windowOptions) => {
const options = {
title: ${JSON.stringify(this.options.app.windowTitle)},
icon: path.resolve(__dirname, ${JSON.stringify(iconName)}),
useContentSize: true,
webPreferences: {
sandbox: true,
contextIsolation: true,
nodeIntegration: false,
},
show: true,
width: 480,
height: 360,
...windowOptions,
};
const activeScreen = screen.getDisplayNearestPoint(screen.getCursorScreenPoint());
const bounds = activeScreen.workArea;
options.x = bounds.x + ((bounds.width - options.width) / 2);
options.y = bounds.y + ((bounds.height - options.height) / 2);
const window = new BrowserWindow(options);
return window;
};
const createProjectWindow = (url) => {
const windowMode = ${JSON.stringify(this.options.app.windowMode)};
const options = {
show: false,
backgroundColor: ${JSON.stringify(this.options.appearance.background)},
width: ${this.computeWindowSize().width},
height: ${this.computeWindowSize().height},
minWidth: 50,
minHeight: 50,
};
// fullscreen === false disables fullscreen on macOS so only set this property when it's true
if (windowMode === 'fullscreen') {
options.fullscreen = true;
}
const window = createWindow(options);
if (windowMode === 'maximize') {
window.maximize();
}
window.loadURL(url);
window.show();
};
const createDataWindow = (dataURI) => {
const window = createWindow({});
window.loadURL(dataURI);
};
const isResourceURL = (url) => {
try {
const parsedUrl = new URL(url);
return parsedUrl.protocol === 'file:' && parsedUrl.href.startsWith(resourcesURL);
} catch (e) {
// ignore
}
return false;
};
const SAFE_PROTOCOLS = [
'https:',
'http:',
'mailto:',
];
const isSafeOpenExternal = (url) => {
try {
const parsedUrl = new URL(url);
return SAFE_PROTOCOLS.includes(parsedUrl.protocol);
} catch (e) {
// ignore
}
return false;
};
const isDataURL = (url) => {
try {
const parsedUrl = new URL(url);
return parsedUrl.protocol === 'data:';
} catch (e) {
// ignore
}
return false;
};
const openLink = (url) => {
if (isDataURL(url)) {
createDataWindow(url);
} else if (isResourceURL(url)) {
createProjectWindow(url);
} else if (isSafeOpenExternal(url)) {
shell.openExternal(url);
}
};
app.on('render-process-gone', (event, webContents, details) => {
const window = BrowserWindow.fromWebContents(webContents);
dialog.showMessageBoxSync(window, {
type: 'error',
title: 'Error',
message: 'Renderer process crashed: ' + details.reason + ' (' + details.exitCode + ')'
});
});
app.on('child-process-gone', (event, details) => {
dialog.showMessageBoxSync({
type: 'error',
title: 'Error',
message: details.type + ' child process crashed: ' + details.reason + ' (' + details.exitCode + ')'
});
});
app.on('web-contents-created', (event, contents) => {
contents.setWindowOpenHandler((details) => {
setImmediate(() => {
openLink(details.url);
});
return {action: 'deny'};
});
contents.on('will-navigate', (e, url) => {
if (!isResourceURL(url)) {
e.preventDefault();
openLink(url);
}
});
contents.on('before-input-event', (e, input) => {
const window = BrowserWindow.fromWebContents(contents);
if (!window || input.type !== "keyDown") return;
if (input.key === 'F11' || (input.key === 'Enter' && input.alt)) {
window.setFullScreen(!window.isFullScreen());
} else if (input.key === 'Escape' && window.isFullScreen()) {
window.setFullScreen(false);
}
});
});
app.on('session-created', (session) => {
session.webRequest.onBeforeRequest({
urls: ["file://*"]
}, (details, callback) => {
callback({
cancel: !details.url.startsWith(resourcesURL)
});
});
});
app.on('window-all-closed', () => {
app.quit();
});
app.whenReady().then(() => {
createProjectWindow(defaultProjectURL);
});
`;
zip.file(`${resourcesPrefix}${electronMainName}`, mainJS);
for (const [path, data] of Object.entries(projectZip.files)) {
setFileFast(zip, `${resourcesPrefix}${path}`, data);
}
if (isWindows) {
const readme = [
'1) Extract the whole zip',
`2) Open "${packageName}.exe" to start the app.`,
'Open "licenses.html" for information regarding open source software used by the app.',
].join('\n\n');
zip.file(`${rootPrefix}README.txt`, readme);
} else if (isMac) {
zip.file(`How to run ${this.options.app.packageName}.txt`, generateMacReadme(this.options));
const plist = this.getPlistPropertiesForPrimaryExecutable();
await this.updatePlist(zip, `${contentsPrefix}Info.plist`, plist);
// macOS Electron apps also contain several helper apps that we should update.
const HELPERS = [
'Electron Helper',
'Electron Helper (GPU)',
'Electron Helper (Renderer)',
'Electron Helper (Plugin)',
];
for (const name of HELPERS) {
await this.updatePlist(zip, `${contentsPrefix}Frameworks/${name}.app/Contents/Info.plist`, {
// In the prebuilt Electron binaries on GitHub, the original app has a CFBundleIdentifier of
// com.github.Electron and all the helpers have com.github.Electron.helper
[CFBundleIdentifier]: `${plist[CFBundleIdentifier]}.helper`,
// We shouldn't change the actual name of the helpers because we don't actually rename their .app
// We also don't rename the executable
[CFBundleDisplayName]: name.replace('Electron', this.options.app.packageName),
// electron-builder always updates the helpers to use the same version as the app itself
[CFBundleVersion]: this.options.app.version,
[CFBundleShortVersionString]: this.options.app.version,
});
}
const icns = await pngToAppleICNS(icon);
zip.file(`${contentsPrefix}Resources/electron.icns`, icns);
} else if (isLinux) {
// Some Linux distributions can't easily open the executable file from the GUI, so we'll add a simple wrapper that people can use instead.
const startScript = `#!/bin/bash
cd "$(dirname "$0")"
./${packageName}`;
zip.file(`${rootPrefix}start.sh`, startScript, {
unixPermissions: 0o100755
});
}
return zip;
}
async addWebViewMac (projectZip) {
validatePackageName(this.options.app.packageName);
const buffer = await this.fetchLargeAsset(this.options.target, 'arraybuffer');
const appZip = await (await getJSZip()).loadAsync(buffer);
// +-- WebView.app
// +-- Contents
// +-- Info.plist
// +-- MacOS
// +-- WebView (executable)
// +-- Resources
// +-- index.html
// +-- application_config.json
// +-- AppIcon.icns
const newAppName = `${this.options.app.packageName}.app`;
const contentsPrefix = `${newAppName}/Contents/`;
const resourcesPrefix = `${newAppName}/Contents/Resources/`;
const zip = new (await getJSZip());
for (const [path, data] of Object.entries(appZip.files)) {
const newPath = path
// Rename the .app itself
.replace('WebView.app', newAppName)
// Rename the executable
.replace(/WebView$/, this.options.app.packageName);
setFileFast(zip, newPath, data);
}
for (const [path, data] of Object.entries(projectZip.files)) {
setFileFast(zip, `${resourcesPrefix}${path}`, data);
}
const icon = await Adapter.getAppIcon(this.options.app.icon);
const icns = await pngToAppleICNS(icon);
zip.file(`${resourcesPrefix}AppIcon.icns`, icns);
zip.remove(`${resourcesPrefix}Assets.car`);
const parsedBackgroundColor = parseInt(this.options.appearance.background.substr(1), 16);
const applicationConfig = {
title: this.options.app.windowTitle,
background: [
// R, G, B [0-255]
parsedBackgroundColor >> 16 & 0xff,
parsedBackgroundColor >> 8 & 0xff,
parsedBackgroundColor & 0xff,
// A [0-1]
1
],
width: this.computeWindowSize().width,
height: this.computeWindowSize().height
};
zip.file(`${resourcesPrefix}application_config.json`, JSON.stringify(applicationConfig));
await this.updatePlist(zip, `${contentsPrefix}Info.plist`, this.getPlistPropertiesForPrimaryExecutable());
zip.file(`How to run ${this.options.app.packageName}.txt`, generateMacReadme(this.options));
return zip;
}
makeWebSocketProvider () {
// If using the default turbowarp.org server, we'll add a fallback for the turbowarp.xyz alias.
// This helps work around web filters as turbowarp.org can be blocked for games and turbowarp.xyz uses
// a problematic TLD. These are the same server and same variables, just different domain.
const cloudHost = this.options.cloudVariables.cloudHost === 'wss://clouddata.turbowarp.org' ? [
'wss://clouddata.turbowarp.org',
'wss://clouddata.turbowarp.xyz'
] : this.options.cloudVariables.cloudHost;
return `new Scaffolding.Cloud.WebSocketProvider(${JSON.stringify(cloudHost)}, ${JSON.stringify(this.options.projectId)})`;
}
makeLocalStorageProvider () {
return `new Scaffolding.Cloud.LocalStorageProvider(${JSON.stringify(`cloudvariables:${this.options.projectId}`)})`;
}
makeCustomProvider () {
const variables = this.options.cloudVariables.custom;
let result = '{const providers = {};\n';
for (const provider of new Set(Object.values(variables))) {
if (provider === 'ws') {
result += `providers.ws = ${this.makeWebSocketProvider()};\n`;
} else if (provider === 'local') {
result += `providers.local = ${this.makeLocalStorageProvider()};\n`;
}
}
result += 'for (const provider of Object.values(providers)) scaffolding.addCloudProvider(provider);\n';
for (const variableName of Object.keys(variables)) {
const providerToUse = variables[variableName];
result += `scaffolding.addCloudProviderOverride(${JSON.stringify(variableName)}, providers[${JSON.stringify(providerToUse)}] || null);\n`;
}
result += '}';
return result;
}
generateFilename (extension) {
return `${this.options.app.windowTitle}.${extension}`;
}
async generateGetProjectData () {
let result = '';
let getProjectDataFunction = '';
let isZip = false;
let storageProgressStart;
let storageProgressEnd;
if (this.options.target === 'html') {
isZip = this.project.type !== 'blob';
storageProgressStart = PROGRESS_FETCHED_COMPRESSED;
storageProgressEnd = PROGRESS_EXTRACTED_COMPRESSED;
// We break the project into a bunch of small segments to be able to show a good progress bar.
const SEGMENT_LENGTH = 100000;
const encoded = encode(this.project.arrayBuffer);
for (let i = 0; i < encoded.length; i += SEGMENT_LENGTH) {
const segment = encoded.substr(i, SEGMENT_LENGTH);
const progress = interpolate(PROGRESS_LOADED_SCRIPTS, PROGRESS_FETCHED_COMPRESSED, i / encoded.length);
// Progress will always be a number between 0 and 1. We can remove the leading 0 and unnecessary decimals to save space.
const shortenedProgress = progress.toString().substr(1, 4);
result += `<script type="p4-project">${segment}</script><script>setProgress(${shortenedProgress})</script>`;
}
getProjectDataFunction = `async () => {
const base85decode = ${decode};
const dataElements = Array.from(document.querySelectorAll('script[type="p4-project"]'));
const result = base85decode(dataElements.map(i => i.textContent).join(''));
dataElements.forEach(i => i.remove());
return result;
}`;
} else {
let src;
if (this.project.type === 'blob' || this.options.target === 'zip-one-asset') {
isZip = this.project.type !== 'blob';
src = './project.zip';
storageProgressStart = PROGRESS_FETCHED_COMPRESSED;
storageProgressEnd = PROGRESS_EXTRACTED_COMPRESSED;
} else {
src = './assets/project.json';
storageProgressStart = PROGRESS_FETCHED_PROJECT_JSON;
storageProgressEnd = PROGRESS_FETCHED_ASSETS;
}
getProjectDataFunction = `() => new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = () => {
resolve(xhr.response);
};
xhr.onerror = () => {
if (location.protocol === 'file:') {
reject(new Error('Zip environment must be used from a website, not from a file URL.'));
} else {
reject(new Error('Request to load project data failed.'));
}
};
xhr.onprogress = (e) => {
if (e.lengthComputable) {
setProgress(interpolate(${PROGRESS_LOADED_SCRIPTS}, ${storageProgressStart}, e.loaded / e.total));
}
};
xhr.responseType = 'arraybuffer';
xhr.open('GET', ${JSON.stringify(src)});
xhr.send();
})`;
}
result += `
<script>
const getProjectData = (function() {
const storage = scaffolding.storage;
storage.onprogress = (total, loaded) => {
setProgress(interpolate(${storageProgressStart}, ${storageProgressEnd}, loaded / total));
};
${isZip ? `
let zip;
// Allow zip to be GC'd after project loads
vm.runtime.on('PROJECT_LOADED', () => (zip = null));
const findFileInZip = (path) => zip.file(path) || zip.file(new RegExp("^([^/]*/)?" + path + "$"))[0];
storage.addHelper({
load: (assetType, assetId, dataFormat) => {
if (!zip) {
throw new Error('Zip is not loaded or has been closed');
}
const path = assetId + '.' + dataFormat;
const file = findFileInZip(path);
if (!file) {
throw new Error('Asset is not in zip: ' + path)
}
return file
.async('uint8array')
.then((data) => storage.createAsset(assetType, dataFormat, data, assetId));
}
});
return () => (${getProjectDataFunction})().then(async (data) => {
zip = await Scaffolding.JSZip.loadAsync(data);
const file = findFileInZip('project.json');
if (!file) {
throw new Error('project.json is not in zip');
}
return file.async('arraybuffer');
});` : `
storage.addWebStore(
[
storage.AssetType.ImageVector,
storage.AssetType.ImageBitmap,
storage.AssetType.Sound,
storage.AssetType.Font
].filter(i => i),
(asset) => new URL('./assets/' + asset.assetId + '.' + asset.dataFormat, location).href
);
return ${getProjectDataFunction};`}
})();
</script>`;
return result;
}
async generateFavicon () {
if (this.options.app.icon === null) {
return '';
}
const data = await Adapter.readAsURL(this.options.app.icon, 'app icon');
return `<link rel="icon" href="${data}">`;