| 16 | * stored as plain JSON in cache directory. |
| 17 | */ |
| 18 | export async function getOrGenerateClientUid(config: Config, logger: Logger): Promise<string> { |
| 19 | const path = join(config.appDir, CLIENT_UID_FILE); |
| 20 | const file = Bun.file(path); |
| 21 | |
| 22 | if (await file.exists()) { |
| 23 | try { |
| 24 | const data = JSON.parse(await file.text()) as ClientUidFile; |
| 25 | if (typeof data.clientUid === 'string' && data.clientUid.startsWith(expectedUidPrefix(config.clientUidPrefix))) { |
| 26 | logger.debug(`Using client UID: ${data.clientUid}`); |
| 27 | return data.clientUid; |
| 28 | } |
| 29 | } catch (error: unknown) { |
| 30 | logger.error(`Failed to load client UID`, error); |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | const clientUid = `${config.clientUidPrefix}-${crypto.randomUUID()}`; |
| 35 | await mkdir(config.appDir, { recursive: true }); |
| 36 | const payload: ClientUidFile = { clientUid }; |
| 37 | await Bun.write(path, `${JSON.stringify(payload, null, 2)}\n`); |
| 38 | |
| 39 | logger.info(`Generated new client UID: ${clientUid}`); |
| 40 | return clientUid; |
| 41 | } |
| 42 | |
| 43 | function expectedUidPrefix(prefix: string): string { |
| 44 | return `${prefix}-`; |