|
| 1 | +#!/usr/bin/env node |
| 2 | +/** |
| 3 | + * Writes `functions/.env` from the current process environment so `firebase deploy` uploads it |
| 4 | + * next to `index.js`. `src/server.ts` loads it via `loadEnv({ path: join(__dirname, '.env') })`. |
| 5 | + * |
| 6 | + * Intended for GitHub Actions (`GITHUB_ACTIONS=true`). Local deploy: set `WRITE_FUNCTIONS_ENV=1` |
| 7 | + * or rely on Cloud Console env / root `.env` for local runs. |
| 8 | + */ |
| 9 | +import { writeFileSync } from 'fs'; |
| 10 | +import { dirname, join } from 'path'; |
| 11 | +import { fileURLToPath } from 'url'; |
| 12 | + |
| 13 | +const rootDir = dirname(dirname(fileURLToPath(import.meta.url))); |
| 14 | +const outPath = join(rootDir, 'functions', '.env'); |
| 15 | + |
| 16 | +/** Keys the SSR bundle reads at runtime on Cloud Functions (keep in sync with deploy workflow env). */ |
| 17 | +const KEYS = [ |
| 18 | + 'MAIL_HOST', |
| 19 | + 'MAIL_PORT', |
| 20 | + 'MAIL_ACCOUNT', |
| 21 | + 'MAIL_PASSWORD', |
| 22 | + 'FIRESTORE_COLLECTION_MESSAGES', |
| 23 | +]; |
| 24 | + |
| 25 | +function shouldRun() { |
| 26 | + return process.env.GITHUB_ACTIONS === 'true' || process.env.WRITE_FUNCTIONS_ENV === '1'; |
| 27 | +} |
| 28 | + |
| 29 | +function escapeValue(v) { |
| 30 | + return String(v) |
| 31 | + .replace(/\\/g, '\\\\') |
| 32 | + .replace(/\r?\n/g, '\\n') |
| 33 | + .replace(/"/g, '\\"'); |
| 34 | +} |
| 35 | + |
| 36 | +function main() { |
| 37 | + if (!shouldRun()) { |
| 38 | + console.log('write-functions-env: skip (not CI; export WRITE_FUNCTIONS_ENV=1 to force)'); |
| 39 | + return; |
| 40 | + } |
| 41 | + |
| 42 | + const lines = []; |
| 43 | + for (const k of KEYS) { |
| 44 | + const v = process.env[k]; |
| 45 | + if (v === undefined || v === '') continue; |
| 46 | + lines.push(`${k}="${escapeValue(v)}"`); |
| 47 | + } |
| 48 | + |
| 49 | + if (lines.length === 0) { |
| 50 | + console.warn('write-functions-env: no matching env keys set; not writing functions/.env'); |
| 51 | + return; |
| 52 | + } |
| 53 | + |
| 54 | + writeFileSync(outPath, `${lines.join('\n')}\n`, 'utf8'); |
| 55 | + console.log(`write-functions-env: wrote ${lines.length} entries to functions/.env`); |
| 56 | +} |
| 57 | + |
| 58 | +main(); |
0 commit comments