@felfhenor/electron 0.0.0-stage → 0.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/config.d.ts +17 -0
- package/config.js +2 -0
- package/discord.d.ts +1 -0
- package/discord.js +53 -0
- package/export.d.ts +1 -0
- package/export.js +57 -0
- package/files.d.ts +20 -0
- package/files.js +156 -0
- package/index.d.ts +3 -0
- package/index.js +140 -0
- package/ipc.d.ts +28 -0
- package/ipc.js +69 -0
- package/jump-list.d.ts +2 -0
- package/jump-list.js +44 -0
- package/lifecycle.d.ts +3 -0
- package/lifecycle.js +21 -0
- package/logging.d.ts +16 -0
- package/logging.js +134 -0
- package/package.json +17 -4
- package/paths.d.ts +8 -0
- package/paths.js +32 -0
- package/preload.d.ts +4 -0
- package/preload.js +47 -0
- package/protocol.d.ts +5 -0
- package/protocol.js +61 -0
- package/save-before-close.d.ts +4 -0
- package/save-before-close.js +72 -0
- package/steam.d.ts +2 -0
- package/steam.js +106 -0
- package/window.d.ts +7 -0
- package/window.js +188 -0
- package/README.md +0 -3
package/config.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export interface FelDesktopConfig {
|
|
2
|
+
id: string;
|
|
3
|
+
name: string;
|
|
4
|
+
appId: string;
|
|
5
|
+
productName: string;
|
|
6
|
+
windowBackground: string;
|
|
7
|
+
minWidth: number;
|
|
8
|
+
minHeight: number;
|
|
9
|
+
titleBar: 'native' | 'overlay';
|
|
10
|
+
steamAppId?: number;
|
|
11
|
+
discordClientId?: string;
|
|
12
|
+
discordLargeImageKey?: string;
|
|
13
|
+
}
|
|
14
|
+
export interface FelElectronOptions {
|
|
15
|
+
config: FelDesktopConfig;
|
|
16
|
+
root: string;
|
|
17
|
+
}
|
package/config.js
ADDED
package/discord.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function discordInit(clientId?: string, largeImageKey?: string): void;
|
package/discord.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.discordInit = discordInit;
|
|
4
|
+
const ipc_1 = require("./ipc");
|
|
5
|
+
const logging_1 = require("./logging");
|
|
6
|
+
let setActivity = () => undefined;
|
|
7
|
+
let pending;
|
|
8
|
+
const text = (value) => typeof value === 'string' && value ? value.slice(0, 128) : undefined;
|
|
9
|
+
function discordConnect(clientId, largeImageKey) {
|
|
10
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
11
|
+
const rpc = require('discord-rpc');
|
|
12
|
+
const client = new rpc.Client({ transport: 'ipc' });
|
|
13
|
+
let startTimestamp;
|
|
14
|
+
client.on('ready', () => {
|
|
15
|
+
(0, logging_1.coreLog)().info('Discord', 'connected');
|
|
16
|
+
setActivity = (presence) => {
|
|
17
|
+
if (!presence) {
|
|
18
|
+
startTimestamp = undefined;
|
|
19
|
+
void client.clearActivity().catch(() => undefined);
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
startTimestamp ??= new Date();
|
|
23
|
+
client
|
|
24
|
+
.setActivity({
|
|
25
|
+
startTimestamp,
|
|
26
|
+
state: text(presence.state) ?? 'Idle',
|
|
27
|
+
details: text(presence.details),
|
|
28
|
+
largeImageKey,
|
|
29
|
+
largeImageText: text(presence.largeImageText),
|
|
30
|
+
})
|
|
31
|
+
.catch((e) => (0, logging_1.coreLog)().warn('Discord', 'could not update activity', e.message));
|
|
32
|
+
};
|
|
33
|
+
setActivity(pending);
|
|
34
|
+
});
|
|
35
|
+
// Expected whenever Discord isn't running.
|
|
36
|
+
client
|
|
37
|
+
.login({ clientId })
|
|
38
|
+
.catch((e) => (0, logging_1.coreLog)().info('Discord', 'not connected', e.message));
|
|
39
|
+
}
|
|
40
|
+
function discordInit(clientId, largeImageKey = 'defaultimage') {
|
|
41
|
+
(0, ipc_1.ipcOn)(ipc_1.CHANNELS.discordPresence, (_event, presence) => {
|
|
42
|
+
pending = presence;
|
|
43
|
+
setActivity(pending);
|
|
44
|
+
});
|
|
45
|
+
if (!clientId)
|
|
46
|
+
return;
|
|
47
|
+
try {
|
|
48
|
+
discordConnect(clientId, largeImageKey);
|
|
49
|
+
}
|
|
50
|
+
catch (e) {
|
|
51
|
+
(0, logging_1.coreLog)().info('Discord', 'not available', e.message);
|
|
52
|
+
}
|
|
53
|
+
}
|
package/export.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function exportWithLogs(gameId: string, bundleJson: string): Promise<boolean>;
|
package/export.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.exportWithLogs = exportWithLogs;
|
|
7
|
+
const zip_js_1 = require("@zip.js/zip.js");
|
|
8
|
+
const electron_1 = require("electron");
|
|
9
|
+
const promises_1 = __importDefault(require("fs/promises"));
|
|
10
|
+
const path_1 = __importDefault(require("path"));
|
|
11
|
+
const files_1 = require("./files");
|
|
12
|
+
const logging_1 = require("./logging");
|
|
13
|
+
const paths_1 = require("./paths");
|
|
14
|
+
// The main process has no web workers to hand compression off to.
|
|
15
|
+
(0, zip_js_1.configure)({ useWebWorkers: false });
|
|
16
|
+
// A locked or odd file is skipped rather than failing the export, since that's when players need it most.
|
|
17
|
+
async function readLogFiles() {
|
|
18
|
+
let names = [];
|
|
19
|
+
try {
|
|
20
|
+
names = (await promises_1.default.readdir((0, paths_1.logsDir)())).filter((n) => n.endsWith('.log'));
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return [];
|
|
24
|
+
}
|
|
25
|
+
const files = await Promise.allSettled(names.map(async (n) => ({
|
|
26
|
+
name: `logs/${n}`,
|
|
27
|
+
data: await promises_1.default.readFile(path_1.default.join((0, paths_1.logsDir)(), n)),
|
|
28
|
+
})));
|
|
29
|
+
return files.flatMap((f) => (f.status === 'fulfilled' ? [f.value] : []));
|
|
30
|
+
}
|
|
31
|
+
async function zip(files) {
|
|
32
|
+
const writer = new zip_js_1.ZipWriter(new zip_js_1.Uint8ArrayWriter());
|
|
33
|
+
for (const { name, data } of files)
|
|
34
|
+
await writer.add(name, new zip_js_1.Uint8ArrayReader(data));
|
|
35
|
+
return writer.close();
|
|
36
|
+
}
|
|
37
|
+
// Written straight to Downloads and revealed, so a player can attach it to a bug report in two clicks.
|
|
38
|
+
async function exportWithLogs(gameId, bundleJson) {
|
|
39
|
+
try {
|
|
40
|
+
await (0, files_1.writesSettled)();
|
|
41
|
+
const files = [
|
|
42
|
+
{ name: 'save.json', data: new TextEncoder().encode(bundleJson) },
|
|
43
|
+
...(await readLogFiles()),
|
|
44
|
+
];
|
|
45
|
+
const stamp = new Date().toISOString().replaceAll(/[:.]/g, '-');
|
|
46
|
+
const target = path_1.default.join(electron_1.app.getPath('downloads'), `${gameId}-save-and-logs-${stamp}.zip`);
|
|
47
|
+
await promises_1.default.mkdir(path_1.default.dirname(target), { recursive: true });
|
|
48
|
+
await promises_1.default.writeFile(target, await zip(files));
|
|
49
|
+
(0, logging_1.coreLog)().info('Export', `exported ${files.length} files`);
|
|
50
|
+
electron_1.shell.showItemInFolder(target);
|
|
51
|
+
return true;
|
|
52
|
+
}
|
|
53
|
+
catch (e) {
|
|
54
|
+
(0, logging_1.coreLog)().error('Export', 'export with logs failed', e);
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
}
|
package/files.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { SaveKind } from './paths';
|
|
2
|
+
interface ReadCopy {
|
|
3
|
+
json: string;
|
|
4
|
+
writtenAt: number;
|
|
5
|
+
}
|
|
6
|
+
export declare function writeQueued(file: string, json: string): Promise<boolean>;
|
|
7
|
+
export declare function writesSettled(): Promise<unknown>;
|
|
8
|
+
export declare function stampOf(json: string): number;
|
|
9
|
+
export declare function readCopy(file: string): Promise<ReadCopy | undefined>;
|
|
10
|
+
export declare function pickNewer(main?: ReadCopy, temp?: ReadCopy): ReadCopy | undefined;
|
|
11
|
+
export declare function quarantinePath(file: string, now?: number): string;
|
|
12
|
+
export declare function quarantineFile(file: string): Promise<boolean>;
|
|
13
|
+
export declare function readSaveFile(kind: SaveKind, dir?: string): Promise<string | undefined>;
|
|
14
|
+
export declare const writeSaveFile: (kind: SaveKind, json: string) => Promise<boolean>;
|
|
15
|
+
export declare const quarantineSaveFile: (kind: SaveKind) => Promise<boolean>;
|
|
16
|
+
export declare function backupList(): Promise<string[]>;
|
|
17
|
+
export declare function backupWrite(id: string, json: string): Promise<boolean>;
|
|
18
|
+
export declare function backupDelete(ids: string[]): Promise<void>;
|
|
19
|
+
export declare function finishWritesBeforeQuit(): void;
|
|
20
|
+
export {};
|
package/files.js
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.quarantineSaveFile = exports.writeSaveFile = void 0;
|
|
7
|
+
exports.writeQueued = writeQueued;
|
|
8
|
+
exports.writesSettled = writesSettled;
|
|
9
|
+
exports.stampOf = stampOf;
|
|
10
|
+
exports.readCopy = readCopy;
|
|
11
|
+
exports.pickNewer = pickNewer;
|
|
12
|
+
exports.quarantinePath = quarantinePath;
|
|
13
|
+
exports.quarantineFile = quarantineFile;
|
|
14
|
+
exports.readSaveFile = readSaveFile;
|
|
15
|
+
exports.backupList = backupList;
|
|
16
|
+
exports.backupWrite = backupWrite;
|
|
17
|
+
exports.backupDelete = backupDelete;
|
|
18
|
+
exports.finishWritesBeforeQuit = finishWritesBeforeQuit;
|
|
19
|
+
const electron_1 = require("electron");
|
|
20
|
+
const promises_1 = __importDefault(require("fs/promises"));
|
|
21
|
+
const path_1 = __importDefault(require("path"));
|
|
22
|
+
const logging_1 = require("./logging");
|
|
23
|
+
const paths_1 = require("./paths");
|
|
24
|
+
async function syncFile(file, contents) {
|
|
25
|
+
const handle = await promises_1.default.open(file, contents === undefined ? 'r+' : 'w');
|
|
26
|
+
try {
|
|
27
|
+
if (contents !== undefined)
|
|
28
|
+
await handle.writeFile(contents, 'utf8');
|
|
29
|
+
await handle.sync();
|
|
30
|
+
}
|
|
31
|
+
finally {
|
|
32
|
+
await handle.close();
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
// Copied rather than renamed so the tmp stays a complete fallback if the copy is cut short.
|
|
36
|
+
async function writeFileNow(file, json) {
|
|
37
|
+
await promises_1.default.mkdir(path_1.default.dirname(file), { recursive: true });
|
|
38
|
+
await syncFile(`${file}.tmp`, json);
|
|
39
|
+
await promises_1.default.copyFile(`${file}.tmp`, file);
|
|
40
|
+
await syncFile(file);
|
|
41
|
+
}
|
|
42
|
+
// Serialized so two writes never interleave on the same tmp file, and quitting can wait for all of them.
|
|
43
|
+
let writeQueue = Promise.resolve();
|
|
44
|
+
function writeQueued(file, json) {
|
|
45
|
+
const write = writeQueue.then(() => writeFileNow(file, json));
|
|
46
|
+
writeQueue = write.catch(() => undefined);
|
|
47
|
+
return write.then(() => true, (e) => {
|
|
48
|
+
(0, logging_1.coreLog)().error('Files', `write failed: ${path_1.default.basename(file)}`, e);
|
|
49
|
+
return false;
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
function writesSettled() {
|
|
53
|
+
return writeQueue;
|
|
54
|
+
}
|
|
55
|
+
function stampOf(json) {
|
|
56
|
+
const parsed = JSON.parse(json);
|
|
57
|
+
return parsed?.writtenAt ?? parsed?.savedAt ?? 0;
|
|
58
|
+
}
|
|
59
|
+
// Undefined only when missing; locked, unreadable or garbled files reject, so they're never mistaken for "no save".
|
|
60
|
+
async function readCopy(file) {
|
|
61
|
+
try {
|
|
62
|
+
const json = await promises_1.default.readFile(file, 'utf8');
|
|
63
|
+
return { json, writtenAt: stampOf(json) };
|
|
64
|
+
}
|
|
65
|
+
catch (e) {
|
|
66
|
+
if (e.code === 'ENOENT')
|
|
67
|
+
return undefined;
|
|
68
|
+
throw e;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
// The tmp is newer when its copy over the main file failed or was cut short.
|
|
72
|
+
function pickNewer(main, temp) {
|
|
73
|
+
return temp && (!main || temp.writtenAt > main.writtenAt) ? temp : main;
|
|
74
|
+
}
|
|
75
|
+
// savefile.json -> savefile.unreadable-<ts>.json, beside it.
|
|
76
|
+
function quarantinePath(file, now = Date.now()) {
|
|
77
|
+
return file.replace(/\.json$/, `.unreadable-${now}.json`);
|
|
78
|
+
}
|
|
79
|
+
// True when the file is safely copied aside (or there's nothing to copy); false while it's still locked.
|
|
80
|
+
async function quarantineFile(file) {
|
|
81
|
+
try {
|
|
82
|
+
await promises_1.default.copyFile(file, quarantinePath(file));
|
|
83
|
+
return true;
|
|
84
|
+
}
|
|
85
|
+
catch (e) {
|
|
86
|
+
if (e.code === 'ENOENT')
|
|
87
|
+
return true;
|
|
88
|
+
(0, logging_1.coreLog)().warn('Files', `could not set ${path_1.default.basename(file)} aside`, e);
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
// A garbled main file beside a good tmp is set aside here, since the renderer sees a good read and will overwrite it;
|
|
93
|
+
// any other failure rejects, and the renderer asks for the quarantine itself.
|
|
94
|
+
async function readSaveFile(kind, dir = (0, paths_1.savesDir)()) {
|
|
95
|
+
await writeQueue;
|
|
96
|
+
const file = (0, paths_1.saveFilePath)(kind, dir);
|
|
97
|
+
const temp = await readCopy(`${file}.tmp`).catch(() => undefined);
|
|
98
|
+
try {
|
|
99
|
+
return pickNewer(await readCopy(file), temp)?.json;
|
|
100
|
+
}
|
|
101
|
+
catch (e) {
|
|
102
|
+
if (!temp || !(await quarantineFile(file)))
|
|
103
|
+
throw e;
|
|
104
|
+
return temp.json;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
const writeSaveFile = (kind, json) => writeQueued((0, paths_1.saveFilePath)(kind), json);
|
|
108
|
+
exports.writeSaveFile = writeSaveFile;
|
|
109
|
+
const quarantineSaveFile = (kind) => quarantineFile((0, paths_1.saveFilePath)(kind));
|
|
110
|
+
exports.quarantineSaveFile = quarantineSaveFile;
|
|
111
|
+
async function listBackupFiles() {
|
|
112
|
+
try {
|
|
113
|
+
return (await promises_1.default.readdir((0, paths_1.backupsDir)())).filter((f) => f.endsWith('.json'));
|
|
114
|
+
}
|
|
115
|
+
catch (e) {
|
|
116
|
+
if (e.code === 'ENOENT')
|
|
117
|
+
return [];
|
|
118
|
+
throw e;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
async function backupList() {
|
|
122
|
+
const files = await listBackupFiles();
|
|
123
|
+
const contents = await Promise.allSettled(files.map((file) => promises_1.default.readFile(path_1.default.join((0, paths_1.backupsDir)(), file), 'utf8')));
|
|
124
|
+
return contents.flatMap((c) => (c.status === 'fulfilled' ? [c.value] : []));
|
|
125
|
+
}
|
|
126
|
+
async function backupWrite(id, json) {
|
|
127
|
+
const target = (0, paths_1.backupFilePath)(id);
|
|
128
|
+
await promises_1.default.mkdir((0, paths_1.backupsDir)(), { recursive: true });
|
|
129
|
+
// Write-then-rename so a crash mid-write never leaves a truncated backup.
|
|
130
|
+
await promises_1.default.writeFile(`${target}.tmp`, json, 'utf8');
|
|
131
|
+
await promises_1.default.rename(`${target}.tmp`, target);
|
|
132
|
+
return true;
|
|
133
|
+
}
|
|
134
|
+
async function backupDelete(ids) {
|
|
135
|
+
const results = await Promise.allSettled(ids.map((id) => promises_1.default.rm((0, paths_1.backupFilePath)(id), { force: true })));
|
|
136
|
+
const failed = results.filter((r) => r.status === 'rejected').length;
|
|
137
|
+
if (failed)
|
|
138
|
+
(0, logging_1.coreLog)().warn('Files', `could not delete ${failed} old backup(s)`);
|
|
139
|
+
}
|
|
140
|
+
// Matches the close-save timeout: long enough for a big write, short enough that a stalled disk can't keep the game open.
|
|
141
|
+
const QUIT_WRITE_TIMEOUT_MS = 5000;
|
|
142
|
+
function finishWritesBeforeQuit() {
|
|
143
|
+
let isFinished = false;
|
|
144
|
+
electron_1.app.on('will-quit', (event) => {
|
|
145
|
+
if (isFinished)
|
|
146
|
+
return;
|
|
147
|
+
event.preventDefault();
|
|
148
|
+
const timeout = new Promise((resolve) => setTimeout(() => resolve('timeout'), QUIT_WRITE_TIMEOUT_MS));
|
|
149
|
+
void Promise.race([writeQueue, timeout]).then((result) => {
|
|
150
|
+
if (result === 'timeout')
|
|
151
|
+
(0, logging_1.coreLog)().warn('Files', 'quitting with a save still being written');
|
|
152
|
+
isFinished = true;
|
|
153
|
+
electron_1.app.quit();
|
|
154
|
+
});
|
|
155
|
+
});
|
|
156
|
+
}
|
package/index.d.ts
ADDED
package/index.js
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.startFelElectron = startFelElectron;
|
|
7
|
+
const electron_1 = require("electron");
|
|
8
|
+
const fs_1 = __importDefault(require("fs"));
|
|
9
|
+
const path_1 = __importDefault(require("path"));
|
|
10
|
+
const discord_1 = require("./discord");
|
|
11
|
+
const export_1 = require("./export");
|
|
12
|
+
const files_1 = require("./files");
|
|
13
|
+
const ipc_1 = require("./ipc");
|
|
14
|
+
const jump_list_1 = require("./jump-list");
|
|
15
|
+
const logging_1 = require("./logging");
|
|
16
|
+
const lifecycle_1 = require("./lifecycle");
|
|
17
|
+
const paths_1 = require("./paths");
|
|
18
|
+
const protocol_1 = require("./protocol");
|
|
19
|
+
const save_before_close_1 = require("./save-before-close");
|
|
20
|
+
const steam_1 = require("./steam");
|
|
21
|
+
const window_1 = require("./window");
|
|
22
|
+
const FOLDERS = {
|
|
23
|
+
saves: paths_1.savesDir,
|
|
24
|
+
logs: paths_1.logsDir,
|
|
25
|
+
backups: paths_1.backupsDir,
|
|
26
|
+
};
|
|
27
|
+
function requireSaveKind(kind) {
|
|
28
|
+
if (!(0, paths_1.isSaveKind)(kind))
|
|
29
|
+
throw new Error(`Unknown save kind: ${String(kind)}`);
|
|
30
|
+
return kind;
|
|
31
|
+
}
|
|
32
|
+
const asText = (value) => typeof value === 'string' ? value : String(value);
|
|
33
|
+
async function openFolder(kind) {
|
|
34
|
+
const folder = FOLDERS[asText(kind)];
|
|
35
|
+
if (!folder)
|
|
36
|
+
throw new Error(`Unknown folder: ${String(kind)}`);
|
|
37
|
+
fs_1.default.mkdirSync(folder(), { recursive: true });
|
|
38
|
+
const error = await electron_1.shell.openPath(folder());
|
|
39
|
+
if (error)
|
|
40
|
+
(0, logging_1.coreLog)().warn('Folders', `could not open ${asText(kind)}`, error);
|
|
41
|
+
}
|
|
42
|
+
function registerFileHandlers(config) {
|
|
43
|
+
(0, ipc_1.ipcHandle)(ipc_1.CHANNELS.filesRead, (kind) => (0, files_1.readSaveFile)(requireSaveKind(kind)));
|
|
44
|
+
(0, ipc_1.ipcHandle)(ipc_1.CHANNELS.filesWrite, (kind, json) => (0, files_1.writeSaveFile)(requireSaveKind(kind), asText(json)));
|
|
45
|
+
(0, ipc_1.ipcHandle)(ipc_1.CHANNELS.filesQuarantine, (kind) => (0, files_1.quarantineSaveFile)(requireSaveKind(kind)));
|
|
46
|
+
(0, ipc_1.ipcHandle)(ipc_1.CHANNELS.backupList, () => (0, files_1.backupList)());
|
|
47
|
+
(0, ipc_1.ipcHandle)(ipc_1.CHANNELS.backupWrite, (id, json) => (0, files_1.backupWrite)(asText(id), asText(json)));
|
|
48
|
+
(0, ipc_1.ipcHandle)(ipc_1.CHANNELS.backupDelete, (ids) => (0, files_1.backupDelete)(Array.isArray(ids) ? ids.map(asText) : []));
|
|
49
|
+
(0, ipc_1.ipcHandle)(ipc_1.CHANNELS.openFolder, (kind) => openFolder(kind));
|
|
50
|
+
(0, ipc_1.ipcHandle)(ipc_1.CHANNELS.exportWithLogs, (json) => (0, export_1.exportWithLogs)(config.id, asText(json)));
|
|
51
|
+
}
|
|
52
|
+
// Everything here comes from the renderer, so it's coerced rather than trusted.
|
|
53
|
+
function registerLogHandler() {
|
|
54
|
+
(0, ipc_1.ipcOn)(ipc_1.CHANNELS.logWrite, (_event, level, category, message) => {
|
|
55
|
+
const safeLevel = logging_1.LOG_LEVELS.includes(level)
|
|
56
|
+
? level
|
|
57
|
+
: 'log';
|
|
58
|
+
(0, logging_1.gameLog)().write(safeLevel, asText(category).slice(0, 200).replaceAll(/\s/g, ' '), asText(message));
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
function loadGame(win, devUrl) {
|
|
62
|
+
const url = devUrl ?? `${ipc_1.APP_ORIGIN}/`;
|
|
63
|
+
(0, logging_1.coreLog)().info('Load', `loading ${url}`);
|
|
64
|
+
win.loadURL(url).catch((e) => (0, logging_1.coreLog)().error('Load', 'loadURL failed', e));
|
|
65
|
+
if (process.argv.includes('--dev'))
|
|
66
|
+
win.webContents.openDevTools();
|
|
67
|
+
}
|
|
68
|
+
async function onReady(options, getWindow, setWindow) {
|
|
69
|
+
// A shipped build never loads anything but its own files, whatever the environment says.
|
|
70
|
+
const devUrl = electron_1.app.isPackaged ? undefined : process.env['APP_URL'];
|
|
71
|
+
if (devUrl)
|
|
72
|
+
(0, ipc_1.ipcAllowOrigin)(new URL(devUrl).origin);
|
|
73
|
+
// Older builds may have registered a service worker that would now serve stale files.
|
|
74
|
+
await electron_1.session.defaultSession
|
|
75
|
+
.clearStorageData({ storages: ['serviceworkers', 'cachestorage'] })
|
|
76
|
+
.catch(() => undefined);
|
|
77
|
+
electron_1.session.defaultSession.setPermissionRequestHandler((_wc, permission, cb) => cb(permission !== 'geolocation'));
|
|
78
|
+
(0, protocol_1.protocolServe)(path_1.default.join(options.root, 'browser'));
|
|
79
|
+
registerFileHandlers(options.config);
|
|
80
|
+
registerLogHandler();
|
|
81
|
+
(0, window_1.windowRegisterHandlers)(getWindow, options.root);
|
|
82
|
+
(0, steam_1.steamRegisterHandlers)();
|
|
83
|
+
(0, discord_1.discordInit)(options.config.discordClientId, options.config.discordLargeImageKey);
|
|
84
|
+
(0, jump_list_1.jumpListRegister)();
|
|
85
|
+
const win = (0, window_1.windowCreate)(options, path_1.default.join(__dirname, 'preload.js'), devUrl ? new URL(devUrl).origin : undefined);
|
|
86
|
+
setWindow(win);
|
|
87
|
+
(0, save_before_close_1.watchSaveBeforeClose)(win);
|
|
88
|
+
(0, lifecycle_1.watchWindowLifecycle)(win);
|
|
89
|
+
loadGame(win, devUrl);
|
|
90
|
+
}
|
|
91
|
+
// Squirrel launches the app with install/uninstall flags to manage shortcuts; those runs must quit at once.
|
|
92
|
+
function isSquirrelLaunch() {
|
|
93
|
+
try {
|
|
94
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
95
|
+
return !!require('electron-squirrel-startup');
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
return false;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
// Every game would otherwise share the template's name, userData folder (saves, storage, logs) and single-instance lock.
|
|
102
|
+
function useGameIdentity(config) {
|
|
103
|
+
electron_1.app.setName(config.productName);
|
|
104
|
+
electron_1.app.setPath('userData', path_1.default.join(electron_1.app.getPath('appData'), config.id));
|
|
105
|
+
}
|
|
106
|
+
// The whole desktop shell; a game's electron/main.js only calls this.
|
|
107
|
+
function startFelElectron(options) {
|
|
108
|
+
useGameIdentity(options.config);
|
|
109
|
+
if (isSquirrelLaunch()) {
|
|
110
|
+
electron_1.app.quit();
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
// A jump list launch only opens a folder, so it skips the lock and log rotation.
|
|
114
|
+
if ((0, jump_list_1.jumpListRunIfLaunched)())
|
|
115
|
+
return;
|
|
116
|
+
// A second copy would tick and save the same game alongside this one.
|
|
117
|
+
if (!electron_1.app.requestSingleInstanceLock()) {
|
|
118
|
+
electron_1.app.exit(0);
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
(0, protocol_1.protocolRegisterScheme)();
|
|
122
|
+
(0, logging_1.initLogging)();
|
|
123
|
+
(0, logging_1.logSessionHeader)();
|
|
124
|
+
(0, lifecycle_1.watchAppLifecycle)();
|
|
125
|
+
(0, steam_1.steamInit)(options.config.steamAppId);
|
|
126
|
+
(0, files_1.finishWritesBeforeQuit)();
|
|
127
|
+
let mainWindow;
|
|
128
|
+
electron_1.app.on('second-instance', () => {
|
|
129
|
+
if (mainWindow)
|
|
130
|
+
(0, window_1.windowBringToFront)(mainWindow);
|
|
131
|
+
});
|
|
132
|
+
electron_1.app.on('window-all-closed', () => {
|
|
133
|
+
if (process.platform !== 'darwin')
|
|
134
|
+
electron_1.app.quit();
|
|
135
|
+
});
|
|
136
|
+
electron_1.app.on('ready', () => void onReady(options, () => mainWindow, (w) => {
|
|
137
|
+
mainWindow = w;
|
|
138
|
+
w.on('closed', () => (mainWindow = undefined));
|
|
139
|
+
}));
|
|
140
|
+
}
|
package/ipc.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { IpcMainEvent, IpcMainInvokeEvent } from 'electron';
|
|
2
|
+
export declare const CHANNELS: {
|
|
3
|
+
readonly filesRead: "fel:files:read";
|
|
4
|
+
readonly filesWrite: "fel:files:write";
|
|
5
|
+
readonly filesQuarantine: "fel:files:quarantine";
|
|
6
|
+
readonly backupList: "fel:backup:list";
|
|
7
|
+
readonly backupWrite: "fel:backup:write";
|
|
8
|
+
readonly backupDelete: "fel:backup:delete";
|
|
9
|
+
readonly logWrite: "fel:log:write";
|
|
10
|
+
readonly openFolder: "fel:open-folder";
|
|
11
|
+
readonly exportWithLogs: "fel:export-with-logs";
|
|
12
|
+
readonly notify: "fel:window:notify";
|
|
13
|
+
readonly flash: "fel:window:flash";
|
|
14
|
+
readonly saveBeforeClose: "fel:window:save-before-close";
|
|
15
|
+
readonly saveBeforeCloseReady: "fel:window:save-before-close:ready";
|
|
16
|
+
readonly saveBeforeCloseDone: "fel:window:save-before-close:done";
|
|
17
|
+
readonly steamAchievements: "fel:steam:achievements";
|
|
18
|
+
readonly steamAchievementClear: "fel:steam:achievement-clear";
|
|
19
|
+
readonly steamPresence: "fel:steam:presence";
|
|
20
|
+
readonly steamInputType: "fel:steam:input-type";
|
|
21
|
+
readonly steamKeyboard: "fel:steam:keyboard";
|
|
22
|
+
readonly discordPresence: "fel:discord:presence";
|
|
23
|
+
};
|
|
24
|
+
export declare const APP_ORIGIN = "app://game";
|
|
25
|
+
export declare function ipcAllowOrigin(origin: string): void;
|
|
26
|
+
export declare function ipcIsTrusted(event: IpcMainEvent | IpcMainInvokeEvent): boolean;
|
|
27
|
+
export declare function ipcHandle(channel: string, handler: (...args: unknown[]) => unknown): void;
|
|
28
|
+
export declare function ipcOn(channel: string, handler: (event: IpcMainEvent, ...args: unknown[]) => void): void;
|
package/ipc.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.APP_ORIGIN = exports.CHANNELS = void 0;
|
|
4
|
+
exports.ipcAllowOrigin = ipcAllowOrigin;
|
|
5
|
+
exports.ipcIsTrusted = ipcIsTrusted;
|
|
6
|
+
exports.ipcHandle = ipcHandle;
|
|
7
|
+
exports.ipcOn = ipcOn;
|
|
8
|
+
const electron_1 = require("electron");
|
|
9
|
+
const logging_1 = require("./logging");
|
|
10
|
+
// The preload repeats these strings (it can't import), and a spec checks the two lists match.
|
|
11
|
+
exports.CHANNELS = {
|
|
12
|
+
filesRead: 'fel:files:read',
|
|
13
|
+
filesWrite: 'fel:files:write',
|
|
14
|
+
filesQuarantine: 'fel:files:quarantine',
|
|
15
|
+
backupList: 'fel:backup:list',
|
|
16
|
+
backupWrite: 'fel:backup:write',
|
|
17
|
+
backupDelete: 'fel:backup:delete',
|
|
18
|
+
logWrite: 'fel:log:write',
|
|
19
|
+
openFolder: 'fel:open-folder',
|
|
20
|
+
exportWithLogs: 'fel:export-with-logs',
|
|
21
|
+
notify: 'fel:window:notify',
|
|
22
|
+
flash: 'fel:window:flash',
|
|
23
|
+
saveBeforeClose: 'fel:window:save-before-close',
|
|
24
|
+
saveBeforeCloseReady: 'fel:window:save-before-close:ready',
|
|
25
|
+
saveBeforeCloseDone: 'fel:window:save-before-close:done',
|
|
26
|
+
steamAchievements: 'fel:steam:achievements',
|
|
27
|
+
steamAchievementClear: 'fel:steam:achievement-clear',
|
|
28
|
+
steamPresence: 'fel:steam:presence',
|
|
29
|
+
steamInputType: 'fel:steam:input-type',
|
|
30
|
+
steamKeyboard: 'fel:steam:keyboard',
|
|
31
|
+
discordPresence: 'fel:discord:presence',
|
|
32
|
+
};
|
|
33
|
+
exports.APP_ORIGIN = 'app://game';
|
|
34
|
+
let allowedOrigins = [exports.APP_ORIGIN];
|
|
35
|
+
function ipcAllowOrigin(origin) {
|
|
36
|
+
allowedOrigins = [...new Set([...allowedOrigins, origin])];
|
|
37
|
+
}
|
|
38
|
+
// Built by hand: URL.origin is "null" for custom schemes outside Chromium's registered list.
|
|
39
|
+
function originOf(url) {
|
|
40
|
+
try {
|
|
41
|
+
const parsed = url ? new URL(url) : undefined;
|
|
42
|
+
return parsed ? `${parsed.protocol}//${parsed.host}` : undefined;
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
// Only the game's own pages may reach the disk; anything navigated or framed in from elsewhere is refused.
|
|
49
|
+
function ipcIsTrusted(event) {
|
|
50
|
+
const origin = originOf(event.senderFrame?.url);
|
|
51
|
+
return !!origin && allowedOrigins.includes(origin);
|
|
52
|
+
}
|
|
53
|
+
function ipcHandle(channel, handler) {
|
|
54
|
+
electron_1.ipcMain.handle(channel, (event, ...args) => {
|
|
55
|
+
if (!ipcIsTrusted(event)) {
|
|
56
|
+
(0, logging_1.coreLog)().warn('Ipc', `refused ${channel} from ${event.senderFrame?.url}`);
|
|
57
|
+
throw new Error('Untrusted sender');
|
|
58
|
+
}
|
|
59
|
+
return handler(...args);
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
function ipcOn(channel, handler) {
|
|
63
|
+
electron_1.ipcMain.on(channel, (event, ...args) => {
|
|
64
|
+
if (ipcIsTrusted(event))
|
|
65
|
+
handler(event, ...args);
|
|
66
|
+
else
|
|
67
|
+
(0, logging_1.coreLog)().warn('Ipc', `refused ${channel} from ${event.senderFrame?.url}`);
|
|
68
|
+
});
|
|
69
|
+
}
|
package/jump-list.d.ts
ADDED
package/jump-list.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.jumpListRunIfLaunched = jumpListRunIfLaunched;
|
|
7
|
+
exports.jumpListRegister = jumpListRegister;
|
|
8
|
+
const electron_1 = require("electron");
|
|
9
|
+
const fs_1 = __importDefault(require("fs"));
|
|
10
|
+
const logging_1 = require("./logging");
|
|
11
|
+
const paths_1 = require("./paths");
|
|
12
|
+
const JUMP_LIST_TASKS = [
|
|
13
|
+
{ flag: '--open-saves', title: 'Open Save Folder', folder: paths_1.savesDir },
|
|
14
|
+
{ flag: '--open-logs', title: 'Open Logs Folder', folder: paths_1.logsDir },
|
|
15
|
+
];
|
|
16
|
+
// Its own short-lived process, so it works the same whether or not the game is running; true when this launch was one.
|
|
17
|
+
function jumpListRunIfLaunched(argv = process.argv) {
|
|
18
|
+
const task = JUMP_LIST_TASKS.find(({ flag }) => argv.includes(flag));
|
|
19
|
+
if (!task)
|
|
20
|
+
return false;
|
|
21
|
+
void electron_1.app
|
|
22
|
+
.whenReady()
|
|
23
|
+
.then(async () => {
|
|
24
|
+
fs_1.default.mkdirSync(task.folder(), { recursive: true });
|
|
25
|
+
await electron_1.shell.openPath(task.folder());
|
|
26
|
+
})
|
|
27
|
+
.finally(() => electron_1.app.exit(0));
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
// Packaged only: a dev run's exe is the shared electron.exe, which can't take the flags alone.
|
|
31
|
+
function jumpListRegister() {
|
|
32
|
+
if (process.platform !== 'win32' || !electron_1.app.isPackaged)
|
|
33
|
+
return;
|
|
34
|
+
const isSet = electron_1.app.setUserTasks(JUMP_LIST_TASKS.map(({ flag, title }) => ({
|
|
35
|
+
program: process.execPath,
|
|
36
|
+
arguments: flag,
|
|
37
|
+
iconPath: process.execPath,
|
|
38
|
+
iconIndex: 0,
|
|
39
|
+
title,
|
|
40
|
+
description: title,
|
|
41
|
+
})));
|
|
42
|
+
if (!isSet)
|
|
43
|
+
(0, logging_1.coreLog)().warn('JumpList', 'could not set jump list tasks');
|
|
44
|
+
}
|
package/lifecycle.d.ts
ADDED
package/lifecycle.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.watchAppLifecycle = watchAppLifecycle;
|
|
4
|
+
exports.watchWindowLifecycle = watchWindowLifecycle;
|
|
5
|
+
const electron_1 = require("electron");
|
|
6
|
+
const logging_1 = require("./logging");
|
|
7
|
+
// A blank window or a crash should always leave a line in core.log saying why.
|
|
8
|
+
function watchAppLifecycle() {
|
|
9
|
+
process.on('uncaughtExceptionMonitor', (e) => (0, logging_1.coreLog)().error('Process', 'uncaught exception', e));
|
|
10
|
+
process.on('unhandledRejection', (reason) => (0, logging_1.coreLog)().error('Process', 'unhandled rejection', reason));
|
|
11
|
+
electron_1.app.on('child-process-gone', (_event, details) => (0, logging_1.coreLog)().warn('Process', `child process gone: ${details.type} ${details.reason}`));
|
|
12
|
+
electron_1.app.on('quit', (_event, code) => (0, logging_1.coreLog)().info('Session', `quit (${code})`));
|
|
13
|
+
}
|
|
14
|
+
function watchWindowLifecycle(win) {
|
|
15
|
+
const contents = win.webContents;
|
|
16
|
+
contents.on('render-process-gone', (_event, details) => (0, logging_1.coreLog)().error('Window', `renderer gone: ${details.reason} (${details.exitCode})`));
|
|
17
|
+
contents.on('did-fail-load', (_event, code, description, url) => (0, logging_1.coreLog)().error('Window', `load failed ${code} ${description}: ${url}`));
|
|
18
|
+
contents.on('preload-error', (_event, preloadPath, error) => (0, logging_1.coreLog)().error('Window', `preload failed: ${preloadPath}`, error));
|
|
19
|
+
win.on('unresponsive', () => (0, logging_1.coreLog)().warn('Window', 'unresponsive'));
|
|
20
|
+
win.on('responsive', () => (0, logging_1.coreLog)().info('Window', 'responsive again'));
|
|
21
|
+
}
|
package/logging.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export declare const LOG_LEVELS: readonly ["debug", "log", "info", "warn", "error"];
|
|
2
|
+
export type LogLevel = (typeof LOG_LEVELS)[number];
|
|
3
|
+
export interface SessionLog {
|
|
4
|
+
write(level: LogLevel, category: string, message: string): void;
|
|
5
|
+
flush(): void;
|
|
6
|
+
info(category: string, ...data: unknown[]): void;
|
|
7
|
+
warn(category: string, ...data: unknown[]): void;
|
|
8
|
+
error(category: string, ...data: unknown[]): void;
|
|
9
|
+
}
|
|
10
|
+
export declare const logFilePath: (name: string, index: number) => string;
|
|
11
|
+
export declare const redactHome: (text: string) => string;
|
|
12
|
+
export declare const formatLine: (level: LogLevel, category: string, message: string) => string;
|
|
13
|
+
export declare function initLogging(): void;
|
|
14
|
+
export declare const coreLog: () => SessionLog;
|
|
15
|
+
export declare const gameLog: () => SessionLog;
|
|
16
|
+
export declare function logSessionHeader(): void;
|