Open History to see the last commit
1#!/usr/bin/env tsx
2/**
3 * Distribute API keys from a source file to all .env and .env.local files in the project.
4 *
5 * Usage: pnpm tsx scripts/distribute-keys.ts <source-file>
6 *
7 * Example: pnpm tsx scripts/distribute-keys.ts ~/keys.env
8 *
9 * The source file should contain KEY=value pairs, one per line.
10 * Keys from the source file will be added/updated in all target env files.
11 * Existing keys not in the source file will be preserved.
12 */
13
14import * as fs from 'node:fs'
15import * as path from 'node:path'
16
17// Static paths for .env.local files
18const STATIC_ENV_LOCAL_PATHS = [
19 'testing/panel/.env.local',
20 'testing/e2e/.env.local',
21 'packages/typescript/ai-code-mode/.env.local',
22 'packages/typescript/ai-anthropic/live-tests/.env.local',
23 'packages/typescript/ai-openai/live-tests/.env.local',
24]
25
26/**
27 * Dynamically find all .env and .env.local files in the examples directory
28 */
29function findExampleEnvFiles(projectRoot: string): string[] {
30 const examplesDir = path.join(projectRoot, 'examples')
31 if (!fs.existsSync(examplesDir)) return []
32
33 const envFiles: string[] = []
34 const examples = fs.readdirSync(examplesDir, { withFileTypes: true })
35
36 for (const entry of examples) {
37 if (!entry.isDirectory()) continue
38
39 const exampleDir = path.join(examplesDir, entry.name)
40
41 // Check for .env.local
42 const envLocalPath = path.join(exampleDir, '.env.local')
43 if (fs.existsSync(envLocalPath)) {
44 envFiles.push(`examples/${entry.name}/.env.local`)
45 }
46
47 // Check for .env
48 const envPath = path.join(exampleDir, '.env')
49 if (fs.existsSync(envPath)) {
50 envFiles.push(`examples/${entry.name}/.env`)
51 }
52 }
53
54 return envFiles
55}
56
57function parseEnvFile(content: string): Map<string, string> {
58 const entries = new Map<string, string>()
59 const lines = content.split('\n')
60
61 for (const line of lines) {
62 const trimmed = line.trim()
63 // Skip empty lines and comments
64 if (!trimmed || trimmed.startsWith('#')) continue
65
66 const eqIndex = trimmed.indexOf('=')
67 if (eqIndex > 0) {
68 const key = trimmed.slice(0, eqIndex).trim()
69 const value = trimmed.slice(eqIndex + 1).trim()
70 entries.set(key, value)
71 }
72 }
73
74 return entries
75}
76
77function serializeEnvFile(entries: Map<string, string>): string {
78 const lines: string[] = []
79 for (const [key, value] of entries) {
80 lines.push(`${key}=${value}`)
81 }
82 return lines.join('\n') + '\n'
83}
84
85function main() {
86 const args = process.argv.slice(2)
87
88 if (args.length === 0) {
89 console.error('Usage: pnpm tsx scripts/distribute-keys.ts <source-file>')
90 console.error('')
91 console.error('Example: pnpm tsx scripts/distribute-keys.ts ~/keys.env')
92 process.exit(1)
93 }
94
95 const sourceFile = args[0]!
96 const resolvedSource = path.resolve(sourceFile)
97
98 if (!fs.existsSync(resolvedSource)) {
99 console.error(`Error: Source file not found: ${resolvedSource}`)
100 process.exit(1)
101 }
102
103 // Read source keys
104 const sourceContent = fs.readFileSync(resolvedSource, 'utf-8')
105 const sourceKeys = parseEnvFile(sourceContent)
106
107 if (sourceKeys.size === 0) {
108 console.error('Error: No keys found in source file')
109 process.exit(1)
110 }
111
112 const projectRoot = path.resolve(import.meta.dirname, '..')
113
114 // Combine static paths with dynamically found example env files
115 const exampleEnvFiles = findExampleEnvFiles(projectRoot)
116 const allEnvPaths = [...STATIC_ENV_LOCAL_PATHS, ...exampleEnvFiles]
117
118 console.log(`📦 Distributing ${sourceKeys.size} key(s) from ${sourceFile}`)
119 console.log(` Keys: ${Array.from(sourceKeys.keys()).join(', ')}`)
120 console.log(` Target files: ${allEnvPaths.length}`)
121 console.log('')
122
123 let updated = 0
124 let created = 0
125 let skipped = 0
126
127 for (const relativePath of allEnvPaths) {
128 const fullPath = path.join(projectRoot, relativePath)
129 const dirPath = path.dirname(fullPath)
130
131 // Skip if directory doesn't exist
132 if (!fs.existsSync(dirPath)) {
133 console.log(`⏭️ Skipped (dir not found): ${relativePath}`)
134 skipped++
135 continue
136 }
137
138 // Read existing file or start fresh
139 let existingKeys = new Map<string, string>()
140 const fileExists = fs.existsSync(fullPath)
141
142 if (fileExists) {
143 const existingContent = fs.readFileSync(fullPath, 'utf-8')
144 existingKeys = parseEnvFile(existingContent)
145 }
146
147 // Merge: source keys override existing keys
148 const mergedKeys = new Map(existingKeys)
149 for (const [key, value] of sourceKeys) {
150 mergedKeys.set(key, value)
151 }
152
153 // Write the merged content
154 const newContent = serializeEnvFile(mergedKeys)
155 fs.writeFileSync(fullPath, newContent)
156
157 if (fileExists) {
158 console.log(`✅ Updated: ${relativePath}`)
159 updated++
160 } else {
161 console.log(`🆕 Created: ${relativePath}`)
162 created++
163 }
164 }
165
166 console.log('')
167 console.log(
168 `Done! Updated: ${updated}, Created: ${created}, Skipped: ${skipped}`,
169 )
170}
171
172main()