/** * 从 .env.tencent 同步 COS 配置到 server/.env * 用法: * node server/scripts/sync-cos-env.mjs # 公网 endpoint(本地调试) * node server/scripts/sync-cos-env.mjs --internal # 内网 endpoint(生产 CVM) */ import fs from 'fs'; import path from 'path'; import { fileURLToPath } from 'url'; import { loadTencentCredentials } from './tencent-lib.mjs'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const defaultTarget = path.join(__dirname, '..', '.env'); const targetPath = process.argv.find((arg) => !arg.startsWith('-') && arg.endsWith('.env')) ? path.resolve(process.argv.find((arg) => arg.endsWith('.env'))) : defaultTarget; const useInternal = process.argv.includes('--internal'); const COS_VARS = { STORAGE_PROVIDER: 's3', S3_BUCKET: 'sku-imge-1343576026', S3_KEY_PREFIX: '', S3_FORCE_PATH_STYLE: 'false', }; function parseEnv(text) { const lines = text.split(/\r?\n/); const map = new Map(); const order = []; for (const line of lines) { const trimmed = line.trim(); if (!trimmed || trimmed.startsWith('#')) { order.push({ type: 'raw', line }); continue; } const i = trimmed.indexOf('='); if (i <= 0) { order.push({ type: 'raw', line }); continue; } const key = trimmed.slice(0, i).trim(); const value = trimmed.slice(i + 1); map.set(key, value); order.push({ type: 'kv', key }); } return { map, order }; } function upsertEnvFile(filePath, updates) { const original = fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf8') : ''; const { map, order } = parseEnv(original); for (const [key, value] of Object.entries(updates)) { if (!map.has(key)) order.push({ type: 'kv', key }); map.set(key, value); } const seen = new Set(); const out = []; for (const item of order) { if (item.type === 'raw') { out.push(item.line); continue; } if (seen.has(item.key)) continue; seen.add(item.key); out.push(`${item.key}=${map.get(item.key) ?? ''}`); } for (const [key, value] of Object.entries(updates)) { if (!seen.has(key)) out.push(`${key}=${value}`); } fs.writeFileSync(filePath, `${out.join('\n').replace(/\n*$/, '')}\n`, 'utf8'); } const { secretId, secretKey, env } = loadTencentCredentials(); const region = env.TENCENT_REGION || 'ap-nanjing'; const updates = { ...COS_VARS, S3_REGION: region, S3_ACCESS_KEY_ID: secretId, S3_SECRET_ACCESS_KEY: secretKey, }; if (useInternal) { updates.S3_INTERNAL_ONLY = 'true'; updates.S3_ENDPOINT = `https://cos.${region}.tencentcos.cn`; updates.S3_PUBLIC_BASE_URL = ''; } else { updates.S3_INTERNAL_ONLY = 'false'; updates.S3_ENDPOINT = `https://cos.${region}.myqcloud.com`; updates.S3_PUBLIC_BASE_URL = `https://sku-imge-1343576026.cos.${region}.myqcloud.com`; } upsertEnvFile(targetPath, updates); console.log(`Updated ${targetPath}`); console.log(` mode=${useInternal ? 'internal' : 'public'}, bucket=${COS_VARS.S3_BUCKET}, region=${region}`);