Skip to content

Commit cba4063

Browse files
committed
refactor: even more consistency + reducing the size of the bundled binary
1 parent b8f54b9 commit cba4063

File tree

4 files changed

+135
-83
lines changed

4 files changed

+135
-83
lines changed

resources/js/electron-plugin/dist/server/php.js

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ function shouldMigrateDatabase(store) {
3333
&& process.env.NODE_ENV !== 'development';
3434
}
3535
function shouldOptimize(store) {
36-
return runningSecureBuild();
36+
return true;
3737
}
3838
function getPhpPort() {
3939
return __awaiter(this, void 0, void 0, function* () {
@@ -45,11 +45,7 @@ function getPhpPort() {
4545
}
4646
function retrievePhpIniSettings() {
4747
return __awaiter(this, void 0, void 0, function* () {
48-
const env = {
49-
NATIVEPHP_RUNNING: 'true',
50-
NATIVEPHP_STORAGE_PATH: storagePath,
51-
NATIVEPHP_DATABASE_PATH: databaseFile,
52-
};
48+
const env = getDefaultEnvironmentVariables();
5349
const phpOptions = {
5450
cwd: appPath,
5551
env
@@ -63,11 +59,7 @@ function retrievePhpIniSettings() {
6359
}
6460
function retrieveNativePHPConfig() {
6561
return __awaiter(this, void 0, void 0, function* () {
66-
const env = {
67-
NATIVEPHP_RUNNING: 'true',
68-
NATIVEPHP_STORAGE_PATH: storagePath,
69-
NATIVEPHP_DATABASE_PATH: databaseFile,
70-
};
62+
const env = getDefaultEnvironmentVariables();
7163
const phpOptions = {
7264
cwd: appPath,
7365
env
@@ -128,7 +120,10 @@ function getAppPath() {
128120
return appPath;
129121
}
130122
function ensureAppFoldersAreAvailable() {
123+
console.log('Copying storage folder...');
124+
console.log('Storage path:', storagePath);
131125
if (!existsSync(storagePath) || process.env.NODE_ENV === 'development') {
126+
console.log("App path:", appPath);
132127
copySync(join(appPath, 'storage'), storagePath);
133128
}
134129
mkdirSync(databasePath, { recursive: true });
@@ -160,11 +155,9 @@ function getDefaultEnvironmentVariables(secret, apiPort) {
160155
APP_ENV: process.env.NODE_ENV === 'development' ? 'local' : 'production',
161156
APP_DEBUG: process.env.NODE_ENV === 'development' ? 'true' : 'false',
162157
LARAVEL_STORAGE_PATH: storagePath,
158+
NATIVEPHP_RUNNING: 'true',
163159
NATIVEPHP_STORAGE_PATH: storagePath,
164160
NATIVEPHP_DATABASE_PATH: databaseFile,
165-
NATIVEPHP_API_URL: `http://localhost:${apiPort}/api/`,
166-
NATIVEPHP_RUNNING: 'true',
167-
NATIVEPHP_SECRET: secret,
168161
NATIVEPHP_USER_HOME_PATH: getPath('home'),
169162
NATIVEPHP_APP_DATA_PATH: getPath('appData'),
170163
NATIVEPHP_USER_DATA_PATH: getPath('userData'),
@@ -176,6 +169,10 @@ function getDefaultEnvironmentVariables(secret, apiPort) {
176169
NATIVEPHP_VIDEOS_PATH: getPath('videos'),
177170
NATIVEPHP_RECENT_PATH: getPath('recent'),
178171
};
172+
if (secret && apiPort) {
173+
variables.NATIVEPHP_API_URL = `http://localhost:${apiPort}/api/`;
174+
variables.NATIVEPHP_SECRET = secret;
175+
}
179176
if (runningSecureBuild()) {
180177
variables.APP_SERVICES_CACHE = join(bootstrapCache, 'services.php');
181178
variables.APP_PACKAGES_CACHE = join(bootstrapCache, 'packages.php');
@@ -222,6 +219,9 @@ function serveApp(secret, apiPort, phpIniSettings) {
222219
}
223220
if (shouldMigrateDatabase(store)) {
224221
console.log('Migrating database...');
222+
if (parseInt(process.env.SHELL_VERBOSITY) > 0) {
223+
console.log('Database path:', databaseFile);
224+
}
225225
let result = callPhpSync(['artisan', 'migrate', '--force'], phpOptions, phpIniSettings);
226226
if (result.status !== 0) {
227227
console.error('Failed to migrate database:', result.stderr.toString());

resources/js/electron-plugin/src/server/php.ts

Lines changed: 32 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import state from "./state.js";
1212
import getPort, {portNumbers} from 'get-port';
1313
import {ProcessResult} from "./ProcessResult.js";
1414

15+
// TODO: maybe in dev, don't go to the userData folder and stay in the Laravel app folder
1516
const storagePath = join(app.getPath('userData'), 'storage')
1617
const databasePath = join(app.getPath('userData'), 'database')
1718
const databaseFile = join(databasePath, 'database.sqlite')
@@ -37,7 +38,8 @@ function shouldOptimize(store) {
3738
* the cached config is not picked up on subsequent launches,
3839
* so we'll just rebuilt it every time for now
3940
*/
40-
return runningSecureBuild();
41+
return true;
42+
// return runningSecureBuild();
4143
// return runningSecureBuild() && store.get('optimized_version') !== app.getVersion();
4244
}
4345

@@ -49,11 +51,7 @@ async function getPhpPort() {
4951
}
5052

5153
async function retrievePhpIniSettings() {
52-
const env = {
53-
NATIVEPHP_RUNNING: 'true',
54-
NATIVEPHP_STORAGE_PATH: storagePath,
55-
NATIVEPHP_DATABASE_PATH: databaseFile,
56-
};
54+
const env = getDefaultEnvironmentVariables() as any;
5755

5856
const phpOptions = {
5957
cwd: appPath,
@@ -70,11 +68,7 @@ async function retrievePhpIniSettings() {
7068
}
7169

7270
async function retrieveNativePHPConfig() {
73-
const env = {
74-
NATIVEPHP_RUNNING: 'true',
75-
NATIVEPHP_STORAGE_PATH: storagePath,
76-
NATIVEPHP_DATABASE_PATH: databaseFile,
77-
};
71+
const env = getDefaultEnvironmentVariables() as any;
7872

7973
const phpOptions = {
8074
cwd: appPath,
@@ -173,9 +167,15 @@ function getAppPath() {
173167
}
174168

175169
function ensureAppFoldersAreAvailable() {
176-
if (!existsSync(storagePath) || process.env.NODE_ENV === 'development') {
177-
copySync(join(appPath, 'storage'), storagePath)
178-
}
170+
171+
// if (!runningSecureBuild()) {
172+
console.log('Copying storage folder...');
173+
console.log('Storage path:', storagePath);
174+
if (!existsSync(storagePath) || process.env.NODE_ENV === 'development') {
175+
console.log("App path:", appPath);
176+
copySync(join(appPath, 'storage'), storagePath)
177+
}
178+
// }
179179

180180
mkdirSync(databasePath, {recursive: true})
181181

@@ -214,9 +214,9 @@ interface EnvironmentVariables {
214214
LARAVEL_STORAGE_PATH: string;
215215
NATIVEPHP_STORAGE_PATH: string;
216216
NATIVEPHP_DATABASE_PATH: string;
217-
NATIVEPHP_API_URL: string;
217+
NATIVEPHP_API_URL?: string;
218218
NATIVEPHP_RUNNING: string;
219-
NATIVEPHP_SECRET: string;
219+
NATIVEPHP_SECRET?: string;
220220
NATIVEPHP_USER_HOME_PATH: string;
221221
NATIVEPHP_APP_DATA_PATH: string;
222222
NATIVEPHP_USER_DATA_PATH: string;
@@ -233,19 +233,18 @@ interface EnvironmentVariables {
233233
APP_CONFIG_CACHE?: string;
234234
APP_ROUTES_CACHE?: string;
235235
APP_EVENTS_CACHE?: string;
236+
VIEW_COMPILED_PATH?: string;
236237
}
237238

238-
function getDefaultEnvironmentVariables(secret, apiPort): EnvironmentVariables {
239+
function getDefaultEnvironmentVariables(secret?: string, apiPort?: number): EnvironmentVariables {
239240
// Base variables with string values (no null values)
240241
let variables: EnvironmentVariables = {
241242
APP_ENV: process.env.NODE_ENV === 'development' ? 'local' : 'production',
242243
APP_DEBUG: process.env.NODE_ENV === 'development' ? 'true' : 'false',
243244
LARAVEL_STORAGE_PATH: storagePath,
245+
NATIVEPHP_RUNNING: 'true',
244246
NATIVEPHP_STORAGE_PATH: storagePath,
245247
NATIVEPHP_DATABASE_PATH: databaseFile,
246-
NATIVEPHP_API_URL: `http://localhost:${apiPort}/api/`,
247-
NATIVEPHP_RUNNING: 'true',
248-
NATIVEPHP_SECRET: secret,
249248
NATIVEPHP_USER_HOME_PATH: getPath('home'),
250249
NATIVEPHP_APP_DATA_PATH: getPath('appData'),
251250
NATIVEPHP_USER_DATA_PATH: getPath('userData'),
@@ -258,13 +257,20 @@ function getDefaultEnvironmentVariables(secret, apiPort): EnvironmentVariables {
258257
NATIVEPHP_RECENT_PATH: getPath('recent'),
259258
};
260259

260+
// Only if the server has already started
261+
if (secret && apiPort) {
262+
variables.NATIVEPHP_API_URL = `http://localhost:${apiPort}/api/`;
263+
variables.NATIVEPHP_SECRET = secret;
264+
}
265+
261266
// Only add cache paths if in production mode
262267
if (runningSecureBuild()) {
263268
variables.APP_SERVICES_CACHE = join(bootstrapCache, 'services.php');
264269
variables.APP_PACKAGES_CACHE = join(bootstrapCache, 'packages.php');
265270
variables.APP_CONFIG_CACHE = join(bootstrapCache, 'config.php');
266271
variables.APP_ROUTES_CACHE = join(bootstrapCache, 'routes-v7.php');
267272
variables.APP_EVENTS_CACHE = join(bootstrapCache, 'events.php');
273+
// variables.VIEW_COMPILED_PATH; // TODO: keep those in the phar file if we can.
268274
}
269275

270276
return variables;
@@ -321,7 +327,12 @@ function serveApp(secret, apiPort, phpIniSettings): Promise<ProcessResult> {
321327

322328
// Migrate the database
323329
if (shouldMigrateDatabase(store)) {
324-
console.log('Migrating database...')
330+
console.log('Migrating database...');
331+
332+
if(parseInt(process.env.SHELL_VERBOSITY) > 0) {
333+
console.log('Database path:', databaseFile);
334+
}
335+
325336
let result = callPhpSync(['artisan', 'migrate', '--force'], phpOptions, phpIniSettings);
326337

327338
if (result.status !== 0) {

src/Commands/BuildCommand.php

Lines changed: 71 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,11 @@ class BuildCommand extends Command
3636
{arch? : The Processor Architecture to build for (x64, x86, arm64)}
3737
{--publish : to publish the app}';
3838

39-
protected $availableOs = ['win', 'linux', 'mac', 'all'];
39+
protected array $availableOs = ['win', 'linux', 'mac', 'all'];
40+
41+
private string $buildCommand;
42+
43+
private string $buildOS;
4044

4145
protected function buildPath(string $path = ''): string
4246
{
@@ -50,36 +54,60 @@ protected function sourcePath(string $path = ''): string
5054

5155
public function handle(): void
5256
{
53-
$os = $this->selectOs($this->argument('os'));
57+
$this->buildOS = $this->selectOs($this->argument('os'));
5458

55-
$buildCommand = 'build';
56-
if ($os != 'all') {
57-
$arch = $this->selectArchitectureForOs($os, $this->argument('arch'));
59+
$this->buildCommand = 'build';
60+
if ($this->buildOS != 'all') {
61+
$arch = $this->selectArchitectureForOs($this->buildOS, $this->argument('arch'));
5862

59-
$os .= $arch != 'all' ? "-{$arch}" : '';
63+
$this->buildOS .= $arch != 'all' ? "-{$arch}" : '';
6064

6165
// Should we publish?
62-
if ($publish = $this->option('publish')) {
63-
$buildCommand = 'publish';
66+
if ($this->option('publish')) {
67+
$this->buildCommand = 'publish';
6468
}
6569
}
6670

67-
$this->preProcess();
71+
if ($this->hasBundled()) {
72+
$this->buildBundle();
73+
} else {
74+
$this->warnUnsecureBuild();
75+
$this->buildUnsecure();
76+
}
77+
}
6878

79+
private function buildBundle(): void
80+
{
6981
$this->setAppName();
7082

83+
$this->updateElectronDependencies();
84+
7185
$this->newLine();
72-
intro('Updating Electron dependencies...');
73-
Process::path(__DIR__.'/../../resources/js/')
74-
->env($this->getEnvironmentVariables())
75-
->forever()
76-
->run('npm ci', function (string $type, string $output) {
77-
echo $output;
78-
});
86+
intro('Copying Bundle to build directory...');
87+
$this->copyBundleToBuildDirectory();
88+
$this->keepRequiredDirectories();
89+
90+
$this->newLine();
91+
$this->copyCertificateAuthorityCertificate();
92+
93+
$this->newLine();
94+
intro('Copying app icons...');
95+
$this->installIcon();
96+
97+
$this->buildOrPublish();
98+
}
99+
100+
private function buildUnsecure(): void
101+
{
102+
$this->preProcess();
103+
104+
$this->setAppName();
105+
106+
$this->updateElectronDependencies();
79107

80108
$this->newLine();
81109
intro('Copying App to build directory...');
82-
$this->copyBundleToBuildDirectory();
110+
$this->copyToBuildDirectory();
83111

84112
$this->newLine();
85113
$this->copyCertificateAuthorityCertificate();
@@ -96,15 +124,7 @@ public function handle(): void
96124
intro('Pruning vendor directory');
97125
$this->pruneVendorDirectory();
98126

99-
$this->newLine();
100-
intro((($publish ?? false) ? 'Publishing' : 'Building')." for {$os}");
101-
Process::path(__DIR__.'/../../resources/js/')
102-
->env($this->getEnvironmentVariables())
103-
->forever()
104-
->tty(SymfonyProcess::isTtySupported() && ! $this->option('no-interaction'))
105-
->run("npm run {$buildCommand}:{$os}", function (string $type, string $output) {
106-
echo $output;
107-
});
127+
$this->buildOrPublish();
108128

109129
$this->postProcess();
110130
}
@@ -129,4 +149,29 @@ protected function getEnvironmentVariables(): array
129149
Updater::environmentVariables(),
130150
);
131151
}
152+
153+
private function updateElectronDependencies(): void
154+
{
155+
$this->newLine();
156+
intro('Updating Electron dependencies...');
157+
Process::path(__DIR__.'/../../resources/js/')
158+
->env($this->getEnvironmentVariables())
159+
->forever()
160+
->run('npm ci', function (string $type, string $output) {
161+
echo $output;
162+
});
163+
}
164+
165+
private function buildOrPublish(): void
166+
{
167+
$this->newLine();
168+
intro((($this->buildCommand == 'publish') ? 'Publishing' : 'Building')." for {$this->buildOS}");
169+
Process::path(__DIR__.'/../../resources/js/')
170+
->env($this->getEnvironmentVariables())
171+
->forever()
172+
->tty(SymfonyProcess::isTtySupported() && ! $this->option('no-interaction'))
173+
->run("npm run {$this->buildCommand}:{$this->buildOS}", function (string $type, string $output) {
174+
echo $output;
175+
});
176+
}
132177
}

src/Traits/CopiesBundleToBuildDirectory.php

Lines changed: 18 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -19,30 +19,26 @@ protected function hasBundled(): bool
1919

2020
public function copyBundleToBuildDirectory(): bool
2121
{
22-
if ($this->hasBundled()) {
23-
24-
$this->line('Copying secure app bundle to build directory...');
25-
$this->line('From: '.realpath(dirname($this->sourcePath(self::$bundlePath))));
26-
$this->line('To: '.realpath(dirname($this->buildPath(self::$bundlePath))));
27-
28-
// TODO: copy only the files that you need.
29-
$this->copyToBuildDirectory();
30-
$filesToCopy = [
31-
self::$bundlePath,
32-
'.env',
33-
];
34-
$filesystem = new Filesystem;
35-
foreach ($filesToCopy as $file) {
36-
$filesystem->copy($this->sourcePath($file), $this->buildPath($file), true);
37-
}
38-
// $this->keepRequiredDirectories();
39-
40-
return true;
22+
$filesystem = new Filesystem;
23+
24+
$this->line('Copying secure app bundle to build directory...');
25+
$this->line('From: '.realpath(dirname($this->sourcePath(self::$bundlePath))));
26+
$this->line('To: '.realpath(dirname($this->buildPath(self::$bundlePath))));
27+
28+
// Clean and create build directory
29+
$filesystem->remove($this->buildPath());
30+
$filesystem->mkdir($this->buildPath());
31+
32+
$filesToCopy = [
33+
self::$bundlePath,
34+
// '.env',
35+
];
36+
foreach ($filesToCopy as $file) {
37+
$filesystem->copy($this->sourcePath($file), $this->buildPath($file), true);
4138
}
39+
// $this->keepRequiredDirectories();
4240

43-
$this->warnUnsecureBuild();
44-
45-
return $this->copyToBuildDirectory();
41+
return true;
4642
}
4743

4844
public function warnUnsecureBuild(): void

0 commit comments

Comments
 (0)