-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cjs
More file actions
363 lines (299 loc) · 8.04 KB
/
main.cjs
File metadata and controls
363 lines (299 loc) · 8.04 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
const { app, BrowserWindow, dialog, shell } = require("electron");
const { spawn } = require("node:child_process");
const fs = require("node:fs");
const http = require("node:http");
const path = require("node:path");
const net = require("node:net");
const SERVER_HOST = "127.0.0.1";
const DEFAULT_SERVER_PORT = 3847;
const SERVER_READY_TIMEOUT_MS = app.isPackaged ? 30_000 : 120_000;
let mainWindow = null;
let serverProcess = null;
let serverOrigin = "";
let isQuitting = false;
function getAppRoot() {
return app.getAppPath();
}
function getDataRoot() {
return app.isPackaged ? app.getPath("userData") : getAppRoot();
}
function getServerWorkingDir() {
const appRoot = getAppRoot();
try {
return fs.statSync(appRoot).isDirectory() ? appRoot : path.dirname(appRoot);
} catch {
return app.isPackaged ? process.resourcesPath : appRoot;
}
}
function getPlaywrightBrowsersPath() {
return app.isPackaged
? path.join(process.resourcesPath, ".playwright-browsers")
: path.join(getAppRoot(), ".playwright-browsers");
}
function getBundledNodePath() {
return path.join(
process.resourcesPath,
"node-runtime",
process.platform === "win32" ? "node.exe" : "node"
);
}
function getPackagedNodeFallback() {
return {
command: process.execPath,
commandArgs: [],
env: {
ELECTRON_RUN_AS_NODE: "1",
},
};
}
function canUseLocalPlaywrightBrowsers() {
return fs.existsSync(getPlaywrightBrowsersPath());
}
function getNextBin() {
return require.resolve("next/dist/bin/next");
}
function getNodeCommand() {
if (!app.isPackaged) {
return {
command:
process.env.TRAWL_NODE_BINARY ||
process.env.npm_node_execpath ||
"node",
commandArgs: [],
env: {},
};
}
const bundledNode = getBundledNodePath();
if (fs.existsSync(bundledNode)) {
return {
command: bundledNode,
commandArgs: [],
env: {},
};
}
return getPackagedNodeFallback();
}
function stopServer() {
if (!serverProcess || serverProcess.killed) {
return;
}
serverProcess.kill("SIGTERM");
setTimeout(() => {
if (serverProcess && !serverProcess.killed) {
serverProcess.kill("SIGKILL");
}
}, 5_000).unref();
}
function findAvailablePort(preferredPort) {
return new Promise((resolvePort, rejectPort) => {
const attempt = (port) => {
const tester = net.createServer();
tester.once("error", (error) => {
if (error && error.code === "EADDRINUSE") {
attempt(port + 1);
return;
}
rejectPort(error);
});
tester.once("listening", () => {
tester.close(() => resolvePort(port));
});
tester.listen(port, SERVER_HOST);
};
attempt(preferredPort);
});
}
function waitForServer(origin) {
const startedAt = Date.now();
return new Promise((resolveReady, rejectReady) => {
const poll = () => {
if (!serverProcess) {
rejectReady(new Error("Next.js server process was not started."));
return;
}
if (serverProcess.exitCode !== null) {
rejectReady(
new Error(`Next.js server exited early with code ${serverProcess.exitCode}.`)
);
return;
}
const request = http.get(origin, (response) => {
response.resume();
resolveReady();
});
request.on("error", () => {
if (Date.now() - startedAt >= SERVER_READY_TIMEOUT_MS) {
rejectReady(new Error(`Timed out waiting for ${origin} to accept connections.`));
return;
}
setTimeout(poll, 400);
});
request.setTimeout(2_000, () => {
request.destroy();
if (Date.now() - startedAt >= SERVER_READY_TIMEOUT_MS) {
rejectReady(new Error(`Timed out waiting for ${origin} to accept connections.`));
return;
}
setTimeout(poll, 400);
});
};
poll();
});
}
function pipeServerLogs() {
if (!serverProcess) {
return;
}
serverProcess.stdout?.on("data", (chunk) => {
process.stdout.write(`[next] ${chunk}`);
});
serverProcess.stderr?.on("data", (chunk) => {
process.stderr.write(`[next] ${chunk}`);
});
}
function formatStartupError(error, command) {
const details = [
`Command: ${command.command}`,
error.code ? `Code: ${error.code}` : null,
error.message ? `Message: ${error.message}` : null,
].filter(Boolean);
return `Failed to launch the local Next.js server.\n\n${details.join("\n")}`;
}
async function startServer() {
const port = await findAvailablePort(
Number.parseInt(process.env.TRAWL_DESKTOP_PORT || "", 10) || DEFAULT_SERVER_PORT
);
serverOrigin = `http://${SERVER_HOST}:${port}`;
const nextArgs = [getNextBin(), app.isPackaged ? "start" : "dev", "-p", String(port), "-H", SERVER_HOST];
const baseEnv = {
...process.env,
HOSTNAME: SERVER_HOST,
NODE_ENV: app.isPackaged ? "production" : "development",
PORT: String(port),
TRAWL_APP_DIR: getAppRoot(),
TRAWL_DATA_DIR: getDataRoot(),
TRAWL_ELECTRON: "1",
};
if (canUseLocalPlaywrightBrowsers()) {
baseEnv.PLAYWRIGHT_BROWSERS_PATH = getPlaywrightBrowsersPath();
}
const primaryCommand = getNodeCommand();
let retriedWithFallback = false;
const launchServer = (nodeCommand) => {
const child = spawn(nodeCommand.command, [...nodeCommand.commandArgs, ...nextArgs], {
cwd: getServerWorkingDir(),
env: {
...baseEnv,
...nodeCommand.env,
},
stdio: ["ignore", "pipe", "pipe"],
});
serverProcess = child;
pipeServerLogs();
child.once("error", (error) => {
if (isQuitting || serverProcess !== child) {
return;
}
if (
app.isPackaged &&
!retriedWithFallback &&
nodeCommand.command !== process.execPath &&
error.code === "ENOENT"
) {
retriedWithFallback = true;
launchServer(getPackagedNodeFallback());
return;
}
void dialog.showErrorBox("Unable to start Trawl", formatStartupError(error, nodeCommand));
app.quit();
});
child.once("exit", (code, signal) => {
if (isQuitting || serverProcess !== child) {
return;
}
const reason =
signal != null
? `signal ${signal}`
: code != null
? `exit code ${code}`
: "an unknown reason";
void dialog.showErrorBox(
"Trawl stopped",
`The local Next.js server stopped unexpectedly (${reason}).`
);
app.quit();
});
};
launchServer(primaryCommand);
await waitForServer(serverOrigin);
}
function handleExternalNavigation(window) {
const isInternalUrl = (targetUrl) => {
try {
return new URL(targetUrl).origin === serverOrigin;
} catch {
return false;
}
};
window.webContents.setWindowOpenHandler(({ url }) => {
if (isInternalUrl(url)) {
return { action: "allow" };
}
void shell.openExternal(url);
return { action: "deny" };
});
window.webContents.on("will-navigate", (event, url) => {
if (isInternalUrl(url)) {
return;
}
event.preventDefault();
void shell.openExternal(url);
});
}
async function createWindow() {
mainWindow = new BrowserWindow({
width: 1440,
height: 960,
minWidth: 1180,
minHeight: 760,
backgroundColor: "#0a0a0a",
title: "Trawl",
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
sandbox: false,
},
});
handleExternalNavigation(mainWindow);
await mainWindow.loadURL(serverOrigin);
mainWindow.on("closed", () => {
mainWindow = null;
});
}
app.on("before-quit", () => {
isQuitting = true;
stopServer();
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
app.on("activate", async () => {
if (!mainWindow) {
await createWindow();
}
});
app
.whenReady()
.then(async () => {
await startServer();
await createWindow();
})
.catch((error) => {
dialog.showErrorBox(
"Unable to start Trawl",
error instanceof Error ? error.message : String(error)
);
app.quit();
});