env variables handling

This commit is contained in:
cpu
2025-03-31 01:26:50 +02:00
parent c2e7bd5f1e
commit 51a1be22d2
15 changed files with 209 additions and 106 deletions

View File

@@ -4,7 +4,6 @@ import * as state from './core/state.js';
import * as ui from './ui/ui.js';
import * as timer from './core/timer.js';
import camera from './ui/camera.js'; // Default export
import { initEnv } from './env-loader.js';
import * as pushSettingsUI from './ui/pushSettingsUI.js'; // Import the new push settings UI module
// Import externalized modules
@@ -21,8 +20,13 @@ async function initialize() {
// 0. Wait for environment variables to load
try {
await initEnv();
console.log("Environment variables loaded");
// Use the ensureEnvLoaded function from config.js to make sure environment variables are loaded
await config.ensureEnvLoaded();
console.log("Environment variables loaded and verified");
// Log the loaded environment variables for debugging
console.log("BACKEND_URL:", config.getBackendUrl());
console.log("PUBLIC_VAPID_KEY:", config.getPublicVapidKey());
} catch (error) {
console.warn("Failed to load environment variables, using defaults:", error);
}

View File

@@ -1,16 +1,36 @@
// config.js
import { getEnv } from './env-loader.js';
import { getEnv, waitForEnv } from './env-loader.js';
export function getPublicVapidKey() {
// Get the VAPID key from environment variables through the env-loader
return getEnv('PUBLIC_VAPID_KEY');
// Initialize environment variables
let envInitialized = false;
let initPromise = null;
// Function to ensure environment variables are loaded
export async function ensureEnvLoaded() {
if (envInitialized) return;
if (!initPromise) {
initPromise = waitForEnv().then(() => {
envInitialized = true;
console.log('Environment variables loaded in config.js');
});
}
return initPromise;
}
// The VAPID key should not be exposed directly in the source code
// Use the getter function instead: getPublicVapidKey()
// Initialize immediately
ensureEnvLoaded();
// Direct access to environment variables (synchronous, may return default values if called too early)
export function getPublicVapidKey() {
return getEnv('PUBLIC_VAPID_KEY');
}
export function getBackendUrl() {
return getEnv('BACKEND_URL');
}
// Get backend URL from environment variables
export const BACKEND_URL = getEnv('BACKEND_URL');
export const FLIC_BUTTON_ID = 'game-button'; // Example ID, might need configuration
export const LOCAL_STORAGE_KEY = 'gameTimerData';

View File

@@ -1,80 +1,56 @@
// env-loader.js
// This module is responsible for loading environment variables from .env file
// This module is responsible for loading environment variables for the PWA
// Store environment variables in a global object
window.ENV_CONFIG = {};
window.ENV_CONFIG = {
// Default values that will be overridden when config.env.js loads
PUBLIC_VAPID_KEY: 'your_public_vapid_key_here',
BACKEND_URL: 'https://your-push-server.example.com'
};
// Function to load environment variables from .env file
// Function to load environment variables from config.env.js
async function loadEnvVariables() {
try {
// Fetch the .env file as text
const response = await fetch('/.env');
// Try to fetch the config.env.js file which will be generated at build time or deployment
const response = await fetch('/config.env.js');
if (!response.ok) {
console.warn('Could not load .env file. Using default values.');
setDefaultEnvValues();
console.warn('Could not load config.env.js file. Using default values.');
return;
}
const envText = await response.text();
const configText = await response.text();
// Parse the .env file content
const envVars = parseEnvFile(envText);
// Store in the global ENV_CONFIG object
window.ENV_CONFIG = { ...window.ENV_CONFIG, ...envVars };
console.log('Environment variables loaded successfully');
// Extract the configuration object from the JavaScript file
// The file should be in format: window.ENV_CONFIG = { key: "value" };
try {
// Create a safe way to evaluate the config file
const configScript = document.createElement('script');
configScript.textContent = configText;
document.head.appendChild(configScript);
document.head.removeChild(configScript);
console.log('Environment variables loaded successfully from config.env.js');
// Dispatch an event to notify that environment variables have been loaded
window.dispatchEvent(new CustomEvent('env-config-loaded', {
detail: { config: window.ENV_CONFIG }
}));
} catch (parseError) {
console.error('Error parsing config.env.js:', parseError);
}
} catch (error) {
console.error('Error loading environment variables:', error);
setDefaultEnvValues();
}
}
// Parse .env file content into key-value pairs
function parseEnvFile(envText) {
const envVars = {};
// Split by lines and process each line
envText.split('\n').forEach(line => {
// Skip empty lines and comments
if (!line || line.trim().startsWith('#')) return;
// Extract key-value pairs
const match = line.match(/^\s*([\w.-]+)\s*=\s*(.*)?\s*$/);
if (match) {
const key = match[1];
let value = match[2] || '';
// Remove quotes if present
if (value.startsWith('"') && value.endsWith('"')) {
value = value.slice(1, -1);
}
envVars[key] = value;
}
});
return envVars;
}
// Set default values for required environment variables
function setDefaultEnvValues() {
window.ENV_CONFIG = {
...window.ENV_CONFIG,
PUBLIC_VAPID_KEY: 'your_public_vapid_key_here',
BACKEND_URL: 'https://your-push-server.example.com'
};
console.log('Using default environment values');
}
// Export function to initialize environment variables
export async function initEnv() {
await loadEnvVariables();
return window.ENV_CONFIG;
}
// Auto-initialize when imported
// Start loading environment variables immediately
initEnv();
// Export access functions for environment variables
@@ -82,7 +58,30 @@ export function getEnv(key, defaultValue = '') {
return window.ENV_CONFIG[key] || defaultValue;
}
// Export a function to wait for environment variables to be loaded
export function waitForEnv() {
return new Promise((resolve) => {
// If we already have non-default values, resolve immediately
if (window.ENV_CONFIG.BACKEND_URL !== 'https://your-push-server.example.com') {
resolve(window.ENV_CONFIG);
return;
}
// Otherwise, wait for the env-config-loaded event
window.addEventListener('env-config-loaded', (event) => {
resolve(event.detail.config);
}, { once: true });
// Set a timeout to resolve with current values if loading takes too long
setTimeout(() => {
console.warn('Environment loading timed out, using current values');
resolve(window.ENV_CONFIG);
}, 3000);
});
}
export default {
initEnv,
getEnv
};
getEnv,
waitForEnv
};

View File

@@ -1,5 +1,5 @@
// pushFlicIntegration.js
import { getPublicVapidKey, BACKEND_URL, FLIC_BUTTON_ID, FLIC_ACTIONS } from '../config.js';
import { getPublicVapidKey, getBackendUrl, FLIC_BUTTON_ID} from '../config.js';
let pushSubscription = null; // Keep track locally if needed
let actionHandlers = {}; // Store handlers for different Flic actions
@@ -28,19 +28,6 @@ function getBasicAuthCredentials() {
return null;
}
// Prompt the user for credentials after permissions are granted
function promptForCredentials() {
console.log('Prompting user for auth credentials.');
const username = prompt('Please enter your username for backend authentication:');
if (!username) return null;
const password = prompt('Please enter your password:');
if (!password) return null;
const credentials = { username, password };
localStorage.setItem('basicAuthCredentials', JSON.stringify(credentials));
return credentials;
}
// Create Basic Auth header string
function createBasicAuthHeader(credentials) {
if (!credentials?.username || !credentials.password) return null;
@@ -167,7 +154,9 @@ async function sendSubscriptionToServer(subscription, buttonId) {
try {
// Add support for handling CORS preflight with credentials
const response = await fetch(`${BACKEND_URL}/subscribe`, {
console.log("BACKEND_URL Key: " + getBackendUrl());
console.log("FLIC_BUTTON_ID Key: " + FLIC_BUTTON_ID);
const response = await fetch(`${getBackendUrl()}/subscribe`, {
method: 'POST',
body: JSON.stringify({ button_id: buttonId, subscription: subscription }),
headers: headers,

View File

@@ -1,5 +1,4 @@
// serviceWorkerManager.js - Service worker registration and Flic integration
import * as config from '../config.js';
import * as pushFlic from './pushFlicIntegration.js';
// Store the action handlers passed from app.js

View File

@@ -1,6 +1,6 @@
// pushSettingsUI.js - UI handling for push notification settings
import { setupPushNotifications } from '../services/serviceWorkerManager.js';
import { FLIC_BUTTON_ID } from '../config.js';
import { FLIC_BUTTON_ID, getBackendUrl} from '../config.js';
// --- DOM Elements ---
const elements = {
@@ -381,20 +381,9 @@ export async function sendSubscriptionToServer() {
'Authorization': createBasicAuthHeader(credentials)
};
// Import the backend URL from config
let backendUrl;
try {
const configModule = await import('../config.js');
backendUrl = configModule.BACKEND_URL;
} catch (error) {
// No alert, just log the error and return
console.error('Could not get backend URL from config:', error);
return;
}
try {
// Make the request to the server
const response = await fetch(`${backendUrl}/subscribe`, {
const response = await fetch(`${getBackendUrl()}/subscribe`, {
method: 'POST',
body: JSON.stringify({
button_id: FLIC_BUTTON_ID,