Skip to content

Commit

Permalink
refactor: do not depend on process.cwd (#96)
Browse files Browse the repository at this point in the history
1. Removed usage of `process.cwd()`, allowing resources etc. to be
fetched from the simbridge directory
2. Updated dependencies to not fall behind too much
3. Refactored build as `pkg-exe-build` does not seem to work with recent
pkg versions
  • Loading branch information
Saschl authored Oct 18, 2023
1 parent cb314a3 commit 9aec31a
Show file tree
Hide file tree
Showing 14 changed files with 20,818 additions and 31,694 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ jobs:
BUILD_DIR_NAME: release
steps:
- name: Checkout source
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: set Node version
uses: actions/setup-node@v3
with:
node-version: 16
node-version: 18
- name: Build Local API
run: |
npm install
Expand Down
3 changes: 2 additions & 1 deletion apps/server/src/config/printer.config.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { registerAs } from '@nestjs/config';
import { getExecutablePath } from 'apps/server/src/utilities/pathUtil';
import { readFileSync } from 'fs';
import { join } from 'path';

const CONFIG_FILENAME = 'resources/properties.json';

export default registerAs('printer', () => {
const configPath = join(process.cwd(), CONFIG_FILENAME);
const configPath = join(getExecutablePath(), CONFIG_FILENAME);
const properties = JSON.parse(readFileSync(configPath, 'utf8'));

return {
Expand Down
3 changes: 2 additions & 1 deletion apps/server/src/config/server.config.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { registerAs } from '@nestjs/config';
import { getExecutablePath } from 'apps/server/src/utilities/pathUtil';
import { readFileSync } from 'fs';
import { join } from 'path';

const CONFIG_FILENAME = 'resources/properties.json';

export default registerAs('server', () => {
const configPath = join(process.cwd(), CONFIG_FILENAME);
const configPath = join(getExecutablePath(), CONFIG_FILENAME);
const properties = JSON.parse(readFileSync(configPath, 'utf8'));

return { port: properties.server.port, hidden: properties.server.hidden, closeWithMSFS: properties.server.closeWithMSFS };
Expand Down
5 changes: 4 additions & 1 deletion apps/server/src/config/winston.service.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import { Injectable } from '@nestjs/common';
import { getExecutablePath } from 'apps/server/src/utilities/pathUtil';
import { WinstonModuleOptions, WinstonModuleOptionsFactory, utilities as nestWinstonModuleUtilities } from 'nest-winston';
import { join } from 'path';
import * as winston from 'winston';
import 'winston-daily-rotate-file';

const consoleTransport = new winston.transports.Console({
level: 'info',
format: winston.format.combine(
winston.format.colorize(),
winston.format.timestamp(),
winston.format.ms(),
nestWinstonModuleUtilities.format.nestLike('FBW-SimBridge', { prettyPrint: true }),
Expand All @@ -16,7 +19,7 @@ const consoleTransport = new winston.transports.Console({
const fileTransport = new winston.transports.DailyRotateFile({
frequency: '24h',
filename: 'fbw-simbridge-%DATE%.log',
dirname: 'resources/logs',
dirname: `${join(getExecutablePath(), 'resources/logs')}`,
datePattern: 'YYYY-MM-DD-HH',
zippedArchive: true,
maxSize: '20m',
Expand Down
13 changes: 7 additions & 6 deletions apps/server/src/interfaces/mcdu.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { NetworkService } from '../utilities/network.service';
@WebSocketGateway({
cors: { origin: '*' },
path: '/interfaces/v1/mcdu',
})
})
export class McduGateway implements OnGatewayInit, OnGatewayConnection {
constructor(
@Inject(serverConfig.KEY) private serverConf: ConfigType<typeof serverConfig>,
Expand All @@ -29,17 +29,18 @@ export class McduGateway implements OnGatewayInit, OnGatewayConnection {

handleConnection(client: WebSocket) {
this.logger.log('Client connected');
client.on('message', (message: String) => {
if (message === 'mcduConnected') {
client.on('message', (message: Buffer) => {
const messageString = message.toString();
if (messageString === 'mcduConnected') {
this.logger.log('Simulator connected');
}
this.server.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
client.send(messageString);
}
});
if (message.startsWith('print:')) {
const { lines } = JSON.parse(message.substring(6));
if (messageString.startsWith('print:')) {
const { lines } = JSON.parse(messageString.substring(6));
this.printerService.print(lines);
}
});
Expand Down
4 changes: 3 additions & 1 deletion apps/server/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import { platform } from 'os';
import { hideConsole } from 'node-hide-console-window';
import * as path from 'path';
import { getExecutablePath } from 'apps/server/src/utilities/pathUtil';
import { ShutDownService } from './utilities/shutdown.service';
import { AppModule } from './app.module';
import { NetworkService } from './utilities/network.service';
Expand Down Expand Up @@ -75,7 +77,7 @@ bootstrap();
function generateResourceFolders() {
dirs.forEach((dir) => {
access(dir, (error) => {
if (error) mkdirSync(dir, { recursive: true });
if (error) mkdirSync(path.join(getExecutablePath(), dir), { recursive: true });
});
});
}
4 changes: 3 additions & 1 deletion apps/server/src/terrain/processing/maphandler.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { GPU, IKernelRunShortcut, Texture } from 'gpu.js';
import { readFile } from 'fs/promises';
import { join } from 'path';
import { getExecutablePath } from 'apps/server/src/utilities/pathUtil';
import {
AircraftStatus,
ElevationProfile,
Expand Down Expand Up @@ -168,7 +170,7 @@ export class MapHandler {

private async readTerrainMap(): Promise<TerrainMap | undefined> {
try {
const buffer = await readFile('./terrain/terrain.map');
const buffer = await readFile(join(getExecutablePath(), './terrain/terrain.map'));
this.logging.info(`Read MB of terrainmap: ${(Buffer.byteLength(buffer) / (1024 * 1024)).toFixed(2)}`);
return new TerrainMap(buffer);
} catch (err) {
Expand Down
19 changes: 10 additions & 9 deletions apps/server/src/utilities/file.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ import { readFileSync, lstatSync } from 'fs';
import * as xml2js from 'xml2js';
import { getDocument, PDFDocumentProxy } from 'pdfjs-dist/legacy/build/pdf';
import { join } from 'path';
import { getExecutablePath } from './pathUtil';
import { pdfToPng } from './pdfConversion';

const pdfjsLib = require('pdfjs-dist/legacy/build/pdf.js');

pdfjsLib.GlobalWorkerOptions.workerSrc = join(process.cwd(), 'node_modules', 'pdfjs-dist', 'build', 'pdf.worker.min.js');
pdfjsLib.GlobalWorkerOptions.workerSrc = join(getExecutablePath(), 'node_modules', 'pdfjs-dist', 'build', 'pdf.worker.min.js');

@Injectable()
export class FileService {
Expand All @@ -21,7 +22,7 @@ export class FileService {
async getFileCount(directory: string): Promise<number> {
try {
this.logger.debug(`Retrieving number of files in folder: ${directory}`);
const dir = join(process.cwd(), directory);
const dir = join(getExecutablePath(), directory);
this.checkFilePathSafety(dir);
const retrievedDir = await readdir(dir, { withFileTypes: true });
const fileNames = retrievedDir.filter((dir) => dir.isFile()).map((dir) => dir.name);
Expand All @@ -37,7 +38,7 @@ export class FileService {
try {
this.logger.debug(`Reading all files in directory: ${directory}`);

const dir = join(process.cwd(), directory);
const dir = join(getExecutablePath(), directory);
this.checkFilePathSafety(dir);
const fileNames = (await readdir(dir, { withFileTypes: true })).filter((dir) => dir.isFile()).map((dir) => dir.name);

Expand All @@ -56,7 +57,7 @@ export class FileService {
async getFilenames(directory: string): Promise<string[]> {
try {
this.logger.debug(`Reading all files in directory: ${directory}`);
const dir = join(process.cwd(), directory);
const dir = join(getExecutablePath(), directory);
this.checkFilePathSafety(dir);
return (await readdir(dir, { withFileTypes: true })).filter((dir) => dir.isFile()).map((dir) => dir.name);
} catch (err) {
Expand All @@ -83,7 +84,7 @@ export class FileService {
try {
this.logger.debug(`Retrieving file: ${fileName} in folder: ${directory}`);

const path = join(process.cwd(), directory, fileName);
const path = join(getExecutablePath(), directory, fileName);
this.checkFilePathSafety(path);

if (!lstatSync(path).isFile()) {
Expand Down Expand Up @@ -112,21 +113,21 @@ export class FileService {
throw new HttpException('Unexpected null byte encountered', HttpStatus.UNPROCESSABLE_ENTITY);
}

if (filePath.indexOf(process.cwd()) !== 0) {
if (filePath.indexOf(getExecutablePath()) !== 0) {
throw new HttpException('Unacceptable file path', HttpStatus.UNPROCESSABLE_ENTITY);
}
}

async getConvertedPdfFile(directory:string, fileName: string, pageNumber: number, scale: number = 4): Promise<StreamableFile> {
// Some PDFs need external cmaps.
const CMAP_URL = `${join(process.cwd(), 'node_modules', 'pdfjs-dist', 'cmaps')}/`;
const CMAP_URL = `${join(getExecutablePath(), 'node_modules', 'pdfjs-dist', 'cmaps')}/`;
const CMAP_PACKED = true;

// Where the standard fonts are located.
const STANDARD_FONT_DATA_URL = `${join(process.cwd(), 'node_modules', 'pdfjs-dist', 'standard_fonts')}/`;
const STANDARD_FONT_DATA_URL = `${join(getExecutablePath(), 'node_modules', 'pdfjs-dist', 'standard_fonts')}/`;

try {
const conversionFilePath = join(process.cwd(), directory, fileName);
const conversionFilePath = join(getExecutablePath(), directory, fileName);

this.checkFilePathSafety(conversionFilePath);

Expand Down
4 changes: 4 additions & 0 deletions apps/server/src/utilities/pathUtil.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import * as path from 'path';

// @ts-ignore
export const getExecutablePath = () => (process.pkg ? path.dirname(process.argv[0]) : process.cwd());
2 changes: 1 addition & 1 deletion apps/server/src/utilities/systray.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export class SysTrayService implements OnApplicationShutdown {
this.exitItem,
],
},
copyDir: false,
copyDir: true,
});

this.sysTray.onClick((action) => {
Expand Down
19 changes: 19 additions & 0 deletions doExe.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// build.js
import exe from '@angablue/exe';

const build = exe({
entry: './dist/main.js',
out: './build/fbw-simbridge.exe',
pkg: ['-C', 'GZip', '-c', './package.json'], // Specify extra pkg arguments
version: '0.4.4',
target: 'node18-win-x64',
icon: './apps/server/src/assets/images/tail.ico',
properties: {
FileDescription: 'fbw-simbridge',
ProductName: 'FlyByWire Simbridge',
LegalCopyright: 'https://flybywiresim.com/',
OriginalFilename: 'fbw-simbridge.exe',
},
});

build.then(() => console.log('Build completed!'));
3 changes: 2 additions & 1 deletion exeBuild.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ module.exports = {
copyright: 'GNU v3',
pkg: {
targets: [
'node16-win-x64',
'node18-win-x64',
],
assets: [
'node_modules/linebreak/src/classes.trie',
Expand All @@ -26,6 +26,7 @@ module.exports = {
'node_modules/file-uri-to-path/**/*.*',
'node_modules/bit-twiddle/**/*.*',
'node_modules/bit-twiddle/**/*.*',
'node_modules/systray2/traybin/**/*.*',
'node_modules/@flybywiresim/msfs-nodejs/**/*.*',
'dist/mcdu/**/*',
'dist/assets/**/*',
Expand Down
Loading

0 comments on commit 9aec31a

Please sign in to comment.