|
| 1 | +import fs from 'node:fs'; |
| 2 | +import path from 'node:path'; |
| 3 | +import { createInterface } from 'node:readline'; |
| 4 | +import jsonConfig from './token-generator.config.json' with { type: 'json' }; |
| 5 | + |
| 6 | +const root = process.cwd(); |
| 7 | + |
| 8 | +const COLOR_GREEN = '\x1b[32m'; |
| 9 | +const COLOR_ORANGE = '\x1b[33m'; |
| 10 | +const COLOR_RESET = '\x1b[0m'; |
| 11 | + |
| 12 | +const ICON_CLOCK = '\u23F0'; |
| 13 | + |
| 14 | +function readLineFromStdin() { |
| 15 | + return new Promise((resolve) => { |
| 16 | + const rl = createInterface({ input: process.stdin }); |
| 17 | + rl.on('line', (line) => { |
| 18 | + resolve(line.trim()); |
| 19 | + rl.close(); |
| 20 | + }); |
| 21 | + }); |
| 22 | +} |
| 23 | + |
| 24 | +function getExp(accessToken) { |
| 25 | + try { |
| 26 | + const [, payload] = accessToken.split('.'); |
| 27 | + const decodedPayload = JSON.parse(Buffer.from(payload, 'base64').toString('utf-8')); |
| 28 | + const expiryTimestamp = decodedPayload.exp; |
| 29 | + return new Date(expiryTimestamp * 1000).toISOString(); |
| 30 | + } catch (_err) { |
| 31 | + return '<unknown>'; |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +for (const env of jsonConfig) { |
| 36 | + process.stdout.write(`Visit ${env.url}\n`); |
| 37 | + process.stdout.write(`${COLOR_ORANGE}Paste access_token:${COLOR_RESET} `); |
| 38 | + const accessToken = await readLineFromStdin(); |
| 39 | + |
| 40 | + const envContent = fs.readFileSync(path.join(root, env.filePath), { encoding: 'utf-8', flag: 'r' }); |
| 41 | + const lines = envContent.split('\n'); |
| 42 | + const tokenLine = `${env.name}=${accessToken}`; |
| 43 | + let tokenLineReplaced = false; |
| 44 | + |
| 45 | + for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) { |
| 46 | + const currentLineContainsToken = lines[lineIndex].includes(`${env.name}=`); |
| 47 | + if (currentLineContainsToken) { |
| 48 | + if (!tokenLineReplaced) { |
| 49 | + // Replace line with correct token |
| 50 | + lines[lineIndex] = tokenLine; |
| 51 | + tokenLineReplaced = true; |
| 52 | + } else if (!lines[lineIndex].startsWith('#')) { |
| 53 | + // Comment out any additional lines containing token if the token has already been replaced |
| 54 | + lines[lineIndex] = `#${lines[lineIndex]}`; |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + if (!tokenLineReplaced) { |
| 60 | + // Add line with token if it did not exist |
| 61 | + lines.push(tokenLine); |
| 62 | + } |
| 63 | + |
| 64 | + process.stdout.write(`• Token ${env.name} expires at ${getExp(accessToken)} ${ICON_CLOCK} \n`); |
| 65 | + |
| 66 | + const newEnvContent = lines.join('\n'); |
| 67 | + fs.writeFileSync(path.join(root, env.filePath), newEnvContent); |
| 68 | +} |
| 69 | + |
| 70 | +process.stdout.write(`${COLOR_GREEN}Token ready, remember to restart dev server${COLOR_RESET} \n`); |
0 commit comments