import { connect } from '@tursodatabase/database'; import { mkdir, readFile, writeFile } from 'node:fs/promises'; import { basename, dirname, join, resolve } from 'node:path'; const databasePath = resolve( process.env.TDR_DATABASE_PATH || './data/shd-build-development.db', ); const storageDirectory = resolve( process.env.TDR_GAME_ICON_STORAGE_PATH || './data/game-icons', ); const timestamp = new Date() .toISOString() .replaceAll(':', '-') .replace(/\.\d{3}Z$/, 'Z'); const outputPath = resolve( process.argv[2] || `./data/backups/managed-images-${timestamp}.json`, ); const database = await connect(databasePath); const rows = await ( await database.prepare('SELECT * FROM managed_images ORDER BY created_at') ).all(); const images = []; for (const row of rows) { if ( typeof row.storage_key !== 'string' || !/^(?:library|talent|brand_set|os_protocol|skill_chip|specialization|specialization_ability|specialization_node|weapon_mod_slot)-[0-9a-f-]{36}\.webp$/i.test( row.storage_key, ) ) { throw new Error( `Invalid managed-image storage key "${String(row.storage_key)}".`, ); } images.push({ row, contentBase64: ( await readFile(join(storageDirectory, row.storage_key)) ).toString('base64'), }); } const bundle = { format: 'shd-build-managed-images', version: 1, createdAt: new Date().toISOString(), sourceDatabase: basename(databasePath), images, }; await mkdir(dirname(outputPath), { recursive: true }); await writeFile(outputPath, `${JSON.stringify(bundle, null, 2)}\n`, { encoding: 'utf8', flag: 'wx', }); console.log(`Exported ${images.length} managed image assets.`); console.log(`Image bundle: ${outputPath}`);