-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathApp.js
More file actions
4046 lines (3493 loc) · 121 KB
/
Copy pathApp.js
File metadata and controls
4046 lines (3493 loc) · 121 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
'use strict';
const os = require('os');
const fs = require('fs');
const path = require('path');
const zlib = require('zlib');
const http = require('http');
const stream = require('stream');
const { promisify } = require('util');
const sharp = require('sharp');
const { AthomAppsAPI, HomeyAPIV2 } = require('homey-api');
const { getAppLocales } = require('homey-lib');
const HomeyLibApp = require('homey-lib').App;
const HomeyLibDevice = require('homey-lib').Device;
const HomeyLibUtil = require('homey-lib').Util;
const colors = require('colors');
const inquirer = require('inquirer');
const tmp = require('tmp-promise');
const tar = require('tar-fs');
const semver = require('semver');
const ignoreWalk = require('ignore-walk');
const fse = require('fs-extra');
const filesize = require('filesize');
const querystring = require('querystring');
const SocketIOServer = require('socket.io');
const SocketIOClient = require('socket.io-client');
const express = require('express');
const childProcess = require('child_process');
const OpenAI = require('openai');
const PQueue = require('p-queue').default;
const AthomApi = require('../services/AthomApi');
const Settings = require('../services/Settings');
const Util = require('./Util');
const Log = require('./Log');
const HomeyCompose = require('./HomeyCompose');
const GitCommands = require('./GitCommands');
const NpmCommands = require('./NpmCommands');
const ZWave = require('./ZWave');
const DockerHelper = require('./DockerHelper');
const exec = promisify(childProcess.exec);
const statAsync = promisify(fs.stat);
const mkdirAsync = promisify(fs.mkdir);
const readFileAsync = promisify(fs.readFile);
const writeFileAsync = promisify(fs.writeFile);
const copyFileAsync = promisify(fs.copyFile);
const readDirAsync = promisify(fs.readdir);
const pipeline = promisify(stream.pipeline);
const INVALID_CHARACTERS = /[^a-zA-Z0-9-_]/g;
const FLOW_TYPES = ['triggers', 'conditions', 'actions'];
class App {
constructor(appPath) {
this.path = path.resolve(appPath);
this._homeyBuildPath = path.join(this.path, '.homeybuild');
this._homeyComposePath = path.join(this.path, '.homeycompose');
this._exiting = false;
this._std = {};
this._git = new GitCommands(appPath);
}
static usesTypeScript({ appPath }) {
const pkgPath = path.join(appPath, 'package.json');
try {
const pkg = fse.readJSONSync(pkgPath);
return Boolean(pkg && pkg.devDependencies && pkg.devDependencies.typescript);
} catch (error) {
// Ignore
}
return false;
}
static usesModules({ appPath }) {
const pkgPath = path.join(appPath, 'package.json');
try {
const pkg = fse.readJSONSync(pkgPath);
return Boolean(pkg && pkg.type === 'module');
} catch (error) {
// Ignore
}
return false;
}
static async transpileToTypescript({ appPath }) {
Log.success('Typescript detected. Compiling...');
try {
let tsconfig;
try {
const { stdout } = await exec('npx tsc --showConfig');
tsconfig = JSON.parse(stdout);
} catch (error) {
throw new Error(
'Tsconfig validation failed: unable to read configuration from `npx tsc --showConfig`.',
);
}
const actualOutDir = tsconfig.compilerOptions?.outDir;
const expectedOutDir = './.homeybuild';
if (actualOutDir !== expectedOutDir) {
throw new Error(
`Expected \`outDir\` to be \`${expectedOutDir}\`, but found \`${actualOutDir || 'undefined'}\``,
);
}
await exec('npm run build', { cwd: appPath });
Log.success('Typescript compilation successful');
} catch (err) {
Log.error('Error occurred while running tsc');
if (err instanceof Error) {
Log(err.message);
} else {
Log(err.stdout);
}
throw new Error('Typescript compilation failed.');
}
}
static async monitorCtrlC(callback) {
process.once('SIGINT', callback); // CTRL+C
process.once('SIGQUIT', callback); // Keyboard quit
process.once('SIGTERM', callback); // `kill` command
}
async _getLocalFileResponse({ serverPort, assetPath }) {
const res = await fetch(`http://localhost:${serverPort}${assetPath}`);
const headers = {
'Content-Type': res.headers.get('Content-Type') || undefined,
'X-Homey-Hash': res.headers.get('X-Homey-Hash') || undefined,
};
const body = Buffer.from(await res.arrayBuffer());
return {
status: res.status,
headers,
body,
};
}
async _uploadBuildArchive({ url, method, headers, archiveStream, size }) {
const response = await fetch(url, {
method,
headers: {
'Content-Length': size,
...headers,
},
body: archiveStream,
duplex: 'half',
});
if (!response.ok) {
throw new Error(response.statusText);
}
}
async validate({ level = 'debug' } = {}) {
await this._validate({ level });
}
async _validate({ level = 'debug' } = {}) {
Log.success('Validating app...');
try {
const validator = new HomeyLibApp(this._homeyBuildPath);
await validator.validate({ level });
Log.success(`App validated successfully against level \`${level}\``);
return true;
} catch (err) {
Log.error(`App did not validate against level \`${level}\`:`);
throw new Error(err.message);
}
}
async build() {
Log.success('Building app...');
await this.preprocess();
const valid = await this._validate();
if (valid !== true)
throw new Error('The app is not valid, please fix the validation issues first.');
Log.success('App built successfully');
}
async run({
clean = false,
remote = false,
skipBuild = false,
linkModules = '',
network,
dockerSocketPath,
} = {}) {
const homey = await AthomApi.getActiveHomey();
// Homey Cloud does not support running apps remotely.
if (homey.platform === 'cloud' && remote === true) {
throw new Error(
'Homey Cloud does not support running apps remotely. Try again without --remote.',
);
}
// Force remote for Homey Pro (2016 — 2019)
if (homey instanceof HomeyAPIV2) {
remote = true;
}
if (remote) {
return this.runRemote({
homey,
clean,
skipBuild,
dockerSocketPath,
});
}
return this.runDocker({
homey,
clean,
skipBuild,
linkModules,
network,
dockerSocketPath,
});
}
async runRemote({ homey, clean, skipBuild, dockerSocketPath, findLinks }) {
homey.devkit.on('std', this._onStd.bind(this));
homey.devkit.on('disconnect', () => {
Log.error('Connection has been lost, attempting to reconnect...');
// reconnect event isn't forwarded from athom api
homey.devkit.once('connect', () => {
Log.success('Connection restored, some logs might be missing');
});
});
await homey.devkit.connect();
this._session = await this.install({
homey,
clean,
skipBuild,
debug: true,
dockerSocketPath,
findLinks,
});
if (clean) {
Log.warning('Purged all Homey App settings');
}
Log.success(`Running \`${this._session.appId}\`, press CTRL+C to quit`);
Log.info(
` — Profile your app's performance at https://go.athom.com/app-profiling?homey=${homey.id}&app=${this._session.appId}`,
);
Log('─────────────── Logging stdout & stderr ───────────────');
App.monitorCtrlC(this._onCtrlC.bind(this));
}
async buildForLocalRunner(skipBuild) {
if (skipBuild) {
Log(colors.yellow('\n⚠ Skipping build steps!\n'));
} else {
await this.preprocess();
}
}
static collectRunnerEnv(inspectPort) {
return {
HOMEY_APP_RUNNER_DEVMODE: process.env.HOMEY_APP_RUNNER_DEVMODE === '1',
HOMEY_APP_RUNNER_PATH: process.env.HOMEY_APP_RUNNER_PATH, // e.g. /Users/username/Git/homey-app-runner/src
HOMEY_APP_RUNNER_CMD: ['node', `--inspect=0.0.0.0:${inspectPort}`, 'index.js'],
HOMEY_APP_RUNNER_ID:
process.env.HOMEY_APP_RUNNER_ID || 'ghcr.io/athombv/homey-app-runner:latest',
HOMEY_APP_RUNNER_SDK_PATH: process.env.HOMEY_APP_RUNNER_SDK_PATH, // e.g. /Users/username/Git/node-homey-apps-sdk-v3
};
}
async runDocker({ homey, clean, skipBuild, linkModules, network, dockerSocketPath, findLinks }) {
// Prepare Docker
const docker = await DockerHelper.ensureDocker({ dockerSocketPath });
// Import get-port ESM
const getPort = await import('get-port');
// Build the App
await this.buildForLocalRunner(skipBuild, { dockerSocketPath, findLinks });
// Validate the App
const valid = await this._validate();
if (valid !== true) throw new Error('Not installing, please fix the validation issues first');
const manifest = App.getManifest({ appPath: this.path });
// Install the App
Log.success('Creating Remote Session...');
const { sessionId } = await homey.devkit
.installApp({
clean,
manifest,
})
.catch((err) => {
if (err.cause && err.cause.error) {
err.message = err.cause.error;
}
throw err;
});
const baseUrl = await homey.baseUrl;
const socketUrl = `${baseUrl}/devkit`;
// Find Inspect Port
const inspectPort = await getPort.default({
port: getPort.portNumbers(9229, 9229 + 100),
});
// Get Environment Variables
Log.success('Preparing Environment Variables...');
const env = await this._getEnv();
if (Object.keys(env).length) {
Log.info(' — Homey.env (env.json)');
Object.keys(env).forEach((key) => {
const value = env[key];
Log.info(` — ${key}=${Util.ellipsis(value)}`);
});
}
let cleanupPromise;
const cleanup = async () => {
if (!cleanupPromise) {
cleanupPromise = Promise.resolve().then(async () => {
Log('───────────────────────────────────────────────────────');
await Promise.all([
// Uninstall the App
Promise.resolve().then(async () => {
Log.success(`Uninstalling \`${manifest.id}\`...`);
try {
await homey.devkit.uninstallApp({ sessionId });
Log.success(`Uninstalled \`${manifest.id}\``);
} catch (err) {
Log.error('Error Uninstalling:', err.message || err.toString());
}
}),
// Delete the Container
DockerHelper.deleteContainerBySessionId(sessionId),
]).catch((err) => {
Log.error(err.message || err.toString());
});
});
}
return cleanupPromise;
};
// Delete already existing containers
await DockerHelper.deleteContainerByManifestAppId(manifest.id);
// Monitor CTRL+C
let exiting = false;
App.monitorCtrlC(() => {
if (exiting) {
process.exit(1);
}
exiting = true;
cleanup()
.catch(() => {})
.finally(() => {
process.exit(0);
});
});
const serverPort = await getPort.default({
port: getPort.portNumbers(30000, 40000),
});
const serverApp = express();
const serverHTTP = http.createServer(serverApp);
// Proxy Icons, add a X-Homey-Hash header
serverApp.get('*.svg', (req, res, next) => {
Util.getFileHash(path.join(this._homeyBuildPath, req.path))
.then((hash) => {
res.header('X-Homey-Hash', hash);
next();
})
.catch((err) => {
if (err.code === 'ENOENT') {
res.status(404);
res.end(`Not Found: ${req.path}`);
} else {
res.status(400);
res.end(err.message || err.toString());
}
});
});
// Proxy local assets
const middlewares = {};
// During development with docker we get the widget public files from the source folder so that
// the app does not have to be restarted when the widget files change. Making a change and
// reloading the widget should fetch the new file.
serverApp.use('/widgets/:widgetId/public', (req, res, next) => {
const widgetId = req.params.widgetId;
if (!middlewares[widgetId]) {
const widgetPath = path.join(this.path, 'widgets', widgetId, 'public');
middlewares[widgetId] = express.static(widgetPath);
}
return middlewares[widgetId](req, res, next);
});
serverApp.use('/', express.static(this._homeyBuildPath));
// Start the HTTP Server
await new Promise((resolve, reject) => {
serverHTTP.listen(serverPort, (err) => {
if (err) return reject(err);
return resolve();
});
});
// Start Socket.IO ServerIO & clientIO
// The app inside Docker talks to 'serverIO'
// The 'clientIO' talks to Homey
Log.success(`Connecting to \`${homey.name}\`...`);
let homeyIOResolve;
let homeyIOReject;
const homeyIOPromise = new Promise((resolve, reject) => {
homeyIOResolve = resolve;
homeyIOReject = reject;
});
const clientIO = await new Promise((resolve, reject) => {
const clientIO = SocketIOClient(socketUrl, {
transports: ['websocket'],
});
clientIO
.on('connect', () => {
resolve(clientIO);
})
.on('connect_error', (err) => {
Log.error(`Error connecting to \`${homey.name}\``);
Log.error(err);
reject(err);
})
.on('error', reject)
.on('disconnect', () => {
Log.error(`Disconnected from \`${homey.name}\``);
cleanup()
.catch()
.finally(() => {
process.exit();
});
})
.on('event', ({ event, data }, callback) => {
homeyIOPromise
.then((homeyIO) => {
homeyIO.emit(
'event',
{
homeyId: homey.id,
event,
data,
},
callback,
);
})
.catch((err) => callback(err));
})
.on('getFile', ({ path }, callback) => {
Promise.resolve()
.then(() => this._getLocalFileResponse({ serverPort, assetPath: path }))
.then((result) => callback(null, result))
.catch((error) => callback(error.message || error.toString()));
})
.on('getImage', ({ ...args }, callback) => {
homeyIOPromise
.then((homeyIO) => {
homeyIO.emit(
'getImage',
{
homeyId: homey.id,
...args,
},
callback,
);
})
.catch((err) => callback(err));
});
});
const serverIO = SocketIOServer(serverHTTP, {
transports: ['websocket'],
reconnect: false,
pingTimeout: 10000,
pingInterval: 30000,
maxHttpBufferSize: 10e6,
});
serverIO.on('connection', (socket) => {
socket
.on('event', ({ homeyId, ...props }, callback) => {
if (homeyId !== homey.id) {
return callback('Invalid Homey ID');
}
// Override 'Homey.api.getLocalUrl'.
// Homey Pro returns the Docker-host, but Homey CLI is not running on the same machine.
if (
props.type === 'request' &&
props.uri === 'homey:manager:api' &&
props.event === 'getLocalUrl'
) {
return homey.baseUrl
.then((result) => callback(null, result))
.catch((err) => callback(err));
}
return clientIO.emit(
'event',
{
sessionId,
...props,
},
callback,
);
})
.emit(
'createClient',
{
homeyId: homey.id,
homeyVersion: homey.version,
homeyPlatform: homey.platform,
homeyPlatformVersion: homey.platformVersion,
homeyPlatformFeatures:
homey.platform === 'local'
? HomeyLibUtil.getPlatformLocalFeatures(homey.model)
: ['camera-streaming', 'ble-advertisements'],
homeyLanguage: homey.language,
},
(err) => {
if (err) {
Log.error('App Crashed. Stack Trace:');
Log.error(err);
exiting = true;
cleanup()
.catch(() => {})
.finally(() => {
process.exit(0);
});
return homeyIOReject(err);
}
return homeyIOResolve(socket);
},
);
});
// Add Icon Hashes to Manifest
// App Icon Hash
manifest.iconHash = await Util.getFileHash(path.join(this.path, 'assets', 'icon.svg'));
// Driver Icon Hashes
if (Array.isArray(manifest.drivers)) {
await Promise.all(
manifest.drivers.map(async (driver) => {
const iconPath = path.join(this.path, 'drivers', driver.id, 'assets', 'icon.svg');
if (await fse.pathExists(iconPath)) {
driver.iconHash = await Util.getFileHash(iconPath);
}
}),
);
}
// Capability Icon Hashes
if (manifest.capabilities) {
await Promise.all(
Object.values(manifest.capabilities).map(async (capability) => {
if (capability.icon) {
const iconPath = path.join(this.path, capability.icon);
capability.iconHash = await Util.getFileHash(iconPath);
}
}),
);
}
// Settings
if (await fse.pathExists(path.join(this.path, 'settings', 'index.html'))) {
manifest.hasSettings = true;
}
// Start the App on Homey
Log.success(`Starting \`${manifest.id}@${manifest.version}\` remotely...`);
await Promise.race([
new Promise((resolve, reject) => {
clientIO.emit(
'start',
{
sessionId,
manifest,
homeyId: homey.id,
appId: manifest.id,
},
(err) => {
if (err) return reject(new Error(err));
return resolve();
},
);
}),
new Promise((_, reject) => {
setTimeout(() => {
reject(new Error('App Start Timeout From Homey'));
}, 10000);
}),
]);
const tmpDir = path.join(os.tmpdir(), 'apps-tmp', manifest.id);
if (homey.platform === 'local') {
await fse.ensureDir(tmpDir);
await fse.emptyDir(tmpDir);
fse.watch(tmpDir, (_, filename) => {
Log.info(`Modified: ${path.join(tmpDir, filename)}`);
});
}
let userdataDirWarned = false;
const userdataDir = path.join(Settings.getSettingsDirectory(), 'apps-userdata', manifest.id);
if (homey.platform === 'local') {
// Ensure the directory exists
await fse.ensureDir(userdataDir);
// Empty userdata when --clean is set
if (clean === true) {
await fse.emptyDir(userdataDir);
}
// Watch /userdata/ for changes, and notify the user the files might become out of sync.
fse.watch(userdataDir, (_, filename) => {
if (userdataDirWarned === false) {
userdataDirWarned = true;
Log.warning(
'Warning: The /userdata folder is not synced with Homey Pro while developing.\nAfter running the app from the Homey App Store, your /userdata may be out of sync.',
);
}
Log.info(`Modified: ${path.join(userdataDir, filename)}`);
});
// Mount /userdata/ to webserver
serverApp.use('/userdata/', express.static(userdataDir));
}
// Create & Run Container
await this.startRunnerContainer(
sessionId,
manifest,
env,
serverPort,
inspectPort,
network,
homey,
tmpDir,
userdataDir,
linkModules,
docker,
);
await cleanup();
process.exit(0);
}
async startRunnerContainer(
sessionId,
manifest,
env,
serverPort,
inspectPort,
network,
homey,
tmpDir,
userdataDir,
linkModules,
docker,
) {
const {
HOMEY_APP_RUNNER_DEVMODE,
HOMEY_APP_RUNNER_PATH,
HOMEY_APP_RUNNER_CMD,
HOMEY_APP_RUNNER_ID,
HOMEY_APP_RUNNER_SDK_PATH,
} = App.collectRunnerEnv(inspectPort);
// Download Image (if there is no local override)
if (!process.env.HOMEY_APP_RUNNER_ID) {
// Check if the image exists, or needs refresh pull
if (
!(await DockerHelper.imageExists(HOMEY_APP_RUNNER_ID)) ||
(await DockerHelper.imageNeedPull(HOMEY_APP_RUNNER_ID))
) {
await DockerHelper.imagePull(HOMEY_APP_RUNNER_ID);
}
}
const host = await DockerHelper.determineHost();
const containerEnv = [
'APP_PATH=/app',
`APP_ENV=${JSON.stringify(env)}`,
`SERVER=ws://${host}:${serverPort}`,
'DEBUG=1',
];
if (HOMEY_APP_RUNNER_DEVMODE) {
containerEnv.push('DEVMODE=1');
}
const containerBinds = [`${this._homeyBuildPath}:/app:ro,z`];
if (HOMEY_APP_RUNNER_PATH !== undefined) {
containerBinds.push(`${HOMEY_APP_RUNNER_PATH}:/homey-app-runner:ro,z`);
}
if (HOMEY_APP_RUNNER_SDK_PATH !== undefined) {
containerBinds.push(
`${HOMEY_APP_RUNNER_SDK_PATH}:/homey-app-runner/node_modules/@athombv/homey-apps-sdk-v3:ro,z`,
);
}
// Mount /userdata & /tmp for platform local
if (homey.platform === 'local') {
containerBinds.push(`${tmpDir}:/tmp:rw,z`, `${userdataDir}:/userdata:rw,z`);
}
// Link Node.js modules as Docker binds.
// Note that we need to read the `name` from the module's package.json to create a correct path.
containerBinds.push(
`${path.join(this._homeyBuildPath, 'node_modules')}:/app/node_modules/:rw,z`,
...linkModules
.split(',')
.filter((linkModule) => !!linkModule)
.map((linkModule) => {
const linkedModulePath = linkModule.trim();
const { name } = fse.readJSONSync(path.join(linkedModulePath, 'package.json'));
return `${linkedModulePath}:/app/node_modules/${name}`;
}),
);
const createOpts = {
name: `homey-app-runner-${sessionId}-${manifest.id}-v${manifest.version}`,
Env: containerEnv,
ExposedPorts: {
[`${inspectPort}/tcp`]: {},
},
Labels: {
'com.athom.session': sessionId,
'com.athom.port': String(serverPort),
'com.athom.app-id': manifest.id,
'com.athom.app-version': manifest.version,
'com.athom.app-runtime': manifest.runtime,
},
HostConfig: {
ReadonlyRootfs: true,
NetworkMode: network,
PortBindings: {
[`${inspectPort}/tcp`]: [
{
HostPort: String(inspectPort),
},
],
},
Binds: containerBinds,
},
};
Log.success(`Starting debugger at 0.0.0.0:${inspectPort}...`);
Log.info(' — Open `about://inspect` in Google Chrome and select the remote target.');
Log.success(`Starting \`${manifest.id}@${manifest.version}\` in a Docker container...`);
Log.info(' — Press CTRL+C to quit.');
Log('─────────────── Logging stdout & stderr ───────────────');
const passThrough = new stream.PassThrough();
passThrough.pipe(process.stdout);
// On Raspberry Pi, an outdated libseccomp crashes the container.
// Help the developer by letting them know to upgrade.
if (process.platform === 'linux') {
passThrough.on('data', (chunk) => {
chunk = chunk.toString();
if (chunk.includes('# Fatal error in , line 0')) {
setTimeout(() => {
Log.error(`
Oops! Node.js inside Docker has crashed. This is a known issue due to an outdated package on Linux.
To fix, simply run:
$ wget http://ftp.debian.org/debian/pool/main/libs/libseccomp/libseccomp2_2.5.3-2_armhf.deb
$ sudo dpkg -i libseccomp2_2.5.3-2_armhf.deb
$ rm libseccomp2_2.5.3-2_armhf.deb
$ sudo systemctl restart docker
`);
}, 1000);
}
});
}
await docker.run(HOMEY_APP_RUNNER_ID, HOMEY_APP_RUNNER_CMD, passThrough, createOpts);
}
async install({ homey, clean = false, skipBuild = false, debug = false } = {}) {
if (homey.platform === 'cloud') {
throw new Error(
'Installing apps is not available on Homey Cloud.\nPlease run your app instead.',
);
}
if (skipBuild) {
Log(colors.yellow('\n⚠ Skipping build steps!\n'));
} else {
await this.preprocess();
}
const valid = await this._validate();
if (valid !== true) throw new Error('Not installing, please fix the validation issues first');
Log.success('Packing Homey App...');
const app = await this._getPackStream({
appPath: skipBuild ? this.path : this._homeyBuildPath,
});
const env = await this._getEnv();
Log.success(`Installing Homey App on \`${homey.name}\` (${await homey.baseUrl})...`);
try {
const result = await homey.devkit.runApp({
app,
env,
debug,
clean,
});
Log.success(`Homey App \`${result.appId}\` successfully installed`);
return result;
} catch (err) {
Log.error(err);
process.exit();
}
}
async preprocess({ copyAppProductionDependencies = true } = {}) {
if (App.hasHomeyCompose({ appPath: this.path }) === false) {
// Note: this checks that we are in a valid homey app folder
App.getManifest({ appPath: this.path });
}
Log.success('Pre-processing app...');
// Build app.json from Homey Compose files
await HomeyCompose.buildIfUsed(App, this.path);
// Clear the .homeybuild/ folder
await fse.remove(this._homeyBuildPath).catch(async (err) => {
// It helps to wait a bit when ENOTEMPTY is thrown.
if (err.code === 'ENOTEMPTY') {
await new Promise((resolve) => setTimeout(resolve, 2000));
return fse.remove(this._homeyBuildPath);
}
throw err;
});
// Copy app source over to .homeybuild/
await this._copyAppSourceFiles();
// Copy production dependencies to .homeybuild/
if (copyAppProductionDependencies) {
await this._copyAppProductionDependencies();
}
// Compile TypeScript files to .homeybuild/
if (App.usesTypeScript({ appPath: this.path })) {
await App.transpileToTypescript({ appPath: this.path });
}
const appJsonPath = path.join(this.path, 'app.json');
// Read app.json file as json.
try {
const appJsonDataRaw = await fs.promises.readFile(appJsonPath, 'utf-8');
const appJsonData = JSON.parse(appJsonDataRaw);
// Ensure package.json contains type: module
if (appJsonData.esm === true) {
const packageJsonPath = path.join(this.path, 'package.json');
try {
const packageJsonDataRaw = await fs.promises.readFile(packageJsonPath, 'utf-8');
const packageJsonData = JSON.parse(packageJsonDataRaw);
packageJsonData.type = 'module';
// Write to build folder.
await fs.promises.writeFile(
path.join(this._homeyBuildPath, 'package.json'),
JSON.stringify(packageJsonData, null, 2),
);
} catch (err) {
Log.error('Error reading the file', err);
}
}
} catch (err) {
Log.error('Error reading the file', err);
}
// Ensure `/.homeybuild` is added to `.gitignore`, if it exists
const gitIgnorePath = path.join(this.path, '.gitignore');
if (await fse.pathExists(gitIgnorePath)) {
const gitIgnore = await fse.readFile(gitIgnorePath, 'utf8');
if (!gitIgnore.includes('.homeybuild')) {
Log.success('Automatically added `/.homeybuild/` to .gitignore');
await fse.writeFile(gitIgnorePath, `${gitIgnore}\n\n# Added by Homey CLI\n/.homeybuild/`);
}
}
}
async _copyAppSourceFiles() {
const sourceFiles = await this._getAppSourceFiles();
for (const filePath of sourceFiles) {
const fullSrc = path.join(this.path, filePath);
const fullDest = path.join(this._homeyBuildPath, filePath);
await fse.copy(fullSrc, fullDest);
}
const appJson = await fs.promises.readFile(path.join(this.path, 'app.json')).then((data) => {
return JSON.parse(data);
});
if (appJson.widgets) {
for (const [widgetId] of Object.entries(appJson.widgets)) {
const previewLightPath = path.join(this.path, 'widgets', widgetId, 'preview-light.png');
const previewDarkPath = path.join(this.path, 'widgets', widgetId, 'preview-dark.png');
// eslint-disable-next-line no-useless-catch
try {
await fs.promises.access(previewLightPath);
await fs.promises.access(previewDarkPath);
const imageLight = sharp(previewLightPath);
const imageDark = sharp(previewDarkPath);
await fs.promises.mkdir(
path.join(this._homeyBuildPath, 'widgets', widgetId, '__assets__'),
{ recursive: true },
);
await Promise.all([
fs.promises.copyFile(
previewLightPath,
path.join(
this._homeyBuildPath,
'widgets',
widgetId,
'__assets__',
'preview-light.png',
),
),
imageLight
.resize(128, 128)
.toFile(
path.join(
this._homeyBuildPath,
'widgets',
widgetId,
'__assets__',
'preview-light@1x.png',
),
),
imageLight
.resize(192, 192)
.toFile(
path.join(
this._homeyBuildPath,
'widgets',
widgetId,
'__assets__',
'preview-light@1.5x.png',