diff --git a/src/commands/env.ts b/src/commands/env.ts new file mode 100644 index 0000000..0acfbfb --- /dev/null +++ b/src/commands/env.ts @@ -0,0 +1,55 @@ +/** + * Env command implementation + * Pull authenticated environment variables into project .env files + */ + +import * as fs from 'fs'; +import * as path from 'path'; +import { getApiKey } from '../utils/config'; +import { ensureAuthenticated } from '../utils/auth'; + +export interface EnvPullOptions { + file?: string; + overwrite?: boolean; +} + +/** + * Pull FIRECRAWL_API_KEY into a local .env file + */ +export async function handleEnvPullCommand( + options: EnvPullOptions = {} +): Promise { + const apiKey = getApiKey() || (await ensureAuthenticated()); + + const envFile = options.file || '.env'; + const envPath = path.resolve(process.cwd(), envFile); + const envKey = 'FIRECRAWL_API_KEY'; + const envLine = `${envKey}=${apiKey}`; + + if (fs.existsSync(envPath)) { + const contents = fs.readFileSync(envPath, 'utf-8'); + const lines = contents.split('\n'); + const existingIndex = lines.findIndex((line) => + line.startsWith(`${envKey}=`) + ); + + if (existingIndex !== -1) { + if (!options.overwrite) { + console.log( + `${envKey} already exists in ${envFile}. Use --overwrite to replace it.` + ); + return; + } + lines[existingIndex] = envLine; + fs.writeFileSync(envPath, lines.join('\n'), 'utf-8'); + console.log(`✓ Updated ${envKey} in ${envFile}`); + } else { + const separator = contents.endsWith('\n') ? '' : '\n'; + fs.appendFileSync(envPath, `${separator}${envLine}\n`, 'utf-8'); + console.log(`✓ Added ${envKey} to ${envFile}`); + } + } else { + fs.writeFileSync(envPath, `${envLine}\n`, 'utf-8'); + console.log(`✓ Created ${envFile} with ${envKey}`); + } +} diff --git a/src/index.ts b/src/index.ts index 9c2946c..7621268 100644 --- a/src/index.ts +++ b/src/index.ts @@ -28,6 +28,7 @@ import { handleLogoutCommand } from './commands/logout'; import { handleInitCommand } from './commands/init'; import { handleSetupCommand } from './commands/setup'; import type { SetupSubcommand } from './commands/setup'; +import { handleEnvPullCommand } from './commands/env'; import { handleStatusCommand } from './commands/status'; import { isUrl, normalizeUrl } from './utils/url'; import { parseScrapeOptions } from './utils/options'; @@ -991,6 +992,18 @@ program await handleSetupCommand(subcommand, options); }); +program + .command('env') + .description('Pull FIRECRAWL_API_KEY into a local .env file') + .option('-f, --file ', 'Target env file (default: .env)') + .option('--overwrite', 'Overwrite existing FIRECRAWL_API_KEY if present') + .action(async (options) => { + await handleEnvPullCommand({ + file: options.file, + overwrite: options.overwrite, + }); + }); + program .command('credit-usage') .description('Get team credit usage information')