mirror of
https://github.com/DayuanJiang/next-ai-draw-io.git
synced 2026-10-04 00:37:48 +08:00
- Apply preset env after app ready, so Windows/Linux get decrypted keys - Never re-encrypt ciphertext; restore env when switching or removing presets - Block navigation away from the app, open external links in the browser, check IPC senders - Keep inherited proxy settings, default NO_PROXY for localhost - Serialize server start/restart, kill stuck processes, follow port changes - Atomic config writes, keep corrupt files as backups, remember the server port - Menu and settings window stay in sync; dev script gets the decrypted preset env - Use app.isPackaged, parse inline .env comments, drop .env files from the bundle
72 lines
2.3 KiB
TypeScript
72 lines
2.3 KiB
TypeScript
import fs from "node:fs"
|
|
import path from "node:path"
|
|
import { app } from "electron"
|
|
|
|
/**
|
|
* Load environment variables from .env file
|
|
* Searches multiple locations in priority order
|
|
*/
|
|
export function loadEnvFile(): void {
|
|
const possiblePaths = [
|
|
// Next to the executable (for portable installations)
|
|
path.join(path.dirname(app.getPath("exe")), ".env"),
|
|
// User data directory (persists across updates)
|
|
path.join(app.getPath("userData"), ".env"),
|
|
// Development: project root
|
|
path.join(app.getAppPath(), ".env.local"),
|
|
path.join(app.getAppPath(), ".env"),
|
|
]
|
|
|
|
for (const envPath of possiblePaths) {
|
|
if (fs.existsSync(envPath)) {
|
|
console.log(`Loading environment from: ${envPath}`)
|
|
loadEnvFromFile(envPath)
|
|
return
|
|
}
|
|
}
|
|
|
|
console.log("No .env file found, using system environment variables")
|
|
}
|
|
|
|
/**
|
|
* Parse and load environment variables from a file
|
|
*/
|
|
function loadEnvFromFile(filePath: string): void {
|
|
try {
|
|
const content = fs.readFileSync(filePath, "utf-8")
|
|
const lines = content.split("\n")
|
|
|
|
for (const line of lines) {
|
|
const trimmed = line.trim()
|
|
|
|
// Skip comments and empty lines
|
|
if (!trimmed || trimmed.startsWith("#")) continue
|
|
|
|
const equalIndex = trimmed.indexOf("=")
|
|
if (equalIndex === -1) continue
|
|
|
|
const key = trimmed.slice(0, equalIndex).trim()
|
|
let value = trimmed.slice(equalIndex + 1).trim()
|
|
|
|
const quote = value[0]
|
|
const closingQuote =
|
|
quote === '"' || quote === "'" ? value.indexOf(quote, 1) : -1
|
|
if (closingQuote > 0) {
|
|
// Quoted value: keep what's inside the quotes and drop
|
|
// anything after them (e.g. a comment)
|
|
value = value.slice(1, closingQuote)
|
|
} else {
|
|
// Unquoted value: drop an inline comment ("value # comment")
|
|
value = value.replace(/\s+#.*$/, "")
|
|
}
|
|
|
|
// Don't override existing environment variables
|
|
if (!(key in process.env)) {
|
|
process.env[key] = value
|
|
}
|
|
}
|
|
} catch (error) {
|
|
console.error(`Failed to load env file ${filePath}:`, error)
|
|
}
|
|
}
|