deckhearth/scripts/import-lorcana.js
varutasu 9abbab6c21
feat(brand): unify on Deck Hearth across in-repo strings + infra (P1 brand decision)
Resolves the launch-blocking 'TCG Vault vs Deck Hearth' inconsistency called out in AGENTS.md line 5 since project setup. Operator gate-0 decision: Deck Hearth wins. Two briefs applied serially. B1 (mechanical): 7-file display + comment sweep. B2 (infrastructure): Redis prefix rename in lib/rate-limit.js (5 prefixes, accept one-time counter reset), package.json + lockfile regen (STOP-on-churn confirmed only name lines changed), admin/alice/bob email rename in seed scripts + login pre-fill + NEW idempotent migration script scripts/migrations/2026-05-24-rename-admin-email.js. Risk 4 PRESERVE applied: test/lib/permission-middleware.test.js retains admin@tcgvault.com literal with 7-line architect-authored why comment (documents pre-fix-auth-bypass bug shape; preserves historical truth per project's gotcha-documentation convention). All 5 D-decisions ratified at gate-1 (Deck Hearth / deck-hearth / deckhearth / admin@deckhearth.com / full deckhearth Redis prefix). Local: lint 128 baseline (B1 + B2), vitest 21/21 (B1 + B2). CI all green: Playwright smoke 3/3 against rebranded preview in 1m4s, forbidden-cors-headers pass, forbidden-endpoints pass, Screenshot diff pass, Vercel deployment complete. Cross-validation lineage: 4th convoy where the same 3-test smoke spec defends auth surface through sweeping change (after PR #15 Layout default-user, PR #19 CORS, PR #20 rate-limit, now this PR #21 brand rename). OPERATOR POST-MERGE ACTION REQUIRED: run 'node scripts/migrations/2026-05-24-rename-admin-email.js' against prod Neon DB before next admin login (ordering: migration FIRST, then any subsequent setup-db invocation). Migration is ESM, idempotent, UNIQUE-collision-safe. PR #21 architect-commit 50ce9ab, B1 ac8c998, B2 1c18d21.
2026-05-25 02:28:29 -05:00

160 lines
No EOL
4.9 KiB
JavaScript

import fetch from 'node-fetch';
import fs from 'fs';
// Lorcana sets to import
const LORCANA_SETS = [
{ code: 'tfc', name: 'The First Chapter', lorcastCode: '1' },
{ code: 'rotf', name: 'Rise of the Floodborn', lorcastCode: '2' },
{ code: 'ink', name: 'Into the Inklands', lorcastCode: '3' }
];
// Helper function to delay execution
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
// Helper function to fetch with retry logic
async function fetchWithRetry(url, maxRetries = 3, delayMs = 2000) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const response = await fetch(url, {
headers: {
'User-Agent': 'Deck-Hearth/1.0',
'Accept': 'application/json'
},
timeout: 30000 // 30 second timeout
});
if (response.ok) {
return response;
}
// If it's a 404, don't retry
if (response.status === 404) {
throw new Error(`Set not found: ${response.status}`);
}
// If it's a 504 or 503, wait longer before retry
if (response.status === 504 || response.status === 503) {
console.log(`Attempt ${attempt}: Got ${response.status}, waiting ${delayMs * attempt}ms before retry...`);
await delay(delayMs * attempt);
continue;
}
throw new Error(`Lorcana API error: ${response.status}`);
} catch (error) {
if (attempt === maxRetries) {
throw error;
}
console.log(`Attempt ${attempt} failed:`, error.message);
await delay(delayMs * attempt);
}
}
}
async function importLorcanaSet(setCode, setName, lorcastCode) {
try {
console.log(`\n🎨 Importing Lorcana set: ${setName} (${setCode})`);
// Fetch cards directly from Lorcast API
const response = await fetchWithRetry(`https://api.lorcast.com/v0/cards/search?q=set:${lorcastCode}&unique=prints`);
const data = await response.json();
const cards = data.results || [];
if (cards.length === 0) {
console.log(`❌ No cards found for set ${setName}`);
return { success: false, error: 'No cards found', importedCount: 0 };
}
console.log(`📊 Found ${cards.length} cards for set ${setName}`);
let importedCount = 0;
let skippedCount = 0;
// Import all cards via our API in a single batch
const importResponse = await fetch('http://localhost:3000/api/cards/import-lorcana', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
setCode: setCode,
setName: setName
})
});
const importResult = await importResponse.json();
if (importResult.success) {
importedCount = importResult.imported || 0;
skippedCount = importResult.skipped || 0;
console.log(`✅ Import completed for ${setName}: ${importedCount} imported, ${skippedCount} skipped`);
} else {
console.log(`❌ Failed to import ${setName}: ${importResult.error}`);
return { success: false, error: importResult.error };
}
return { success: true, importedCount, skippedCount, total: cards.length };
} catch (error) {
console.log(`❌ Error importing ${setName}: ${error.message}`);
return { success: false, error: error.message };
}
}
async function importAllLorcana() {
console.log('🎨 Starting Lorcana card import...\n');
const results = {
total: 0,
successful: 0,
failed: 0,
sets: []
};
for (const set of LORCANA_SETS) {
const result = await importLorcanaSet(set.code, set.name, set.lorcastCode);
results.sets.push({ ...set, ...result });
if (result.success) {
results.successful++;
results.total += result.importedCount || 0;
} else {
results.failed++;
}
// Add a delay between sets
await delay(2000);
}
// Print summary
console.log('\n📊 Lorcana Import Summary:');
console.log('========================');
console.log(`Total sets: ${LORCANA_SETS.length}`);
console.log(`Successful: ${results.successful}`);
console.log(`Failed: ${results.failed}`);
console.log(`Total cards imported: ${results.total}`);
console.log(`Success rate: ${((results.successful / LORCANA_SETS.length) * 100).toFixed(1)}%`);
// Save detailed results
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const filename = `lorcana-import-results-${timestamp}.json`;
fs.writeFileSync(filename, JSON.stringify(results, null, 2));
console.log(`\n📄 Detailed results saved to: ${filename}`);
return results;
}
// Run the import if this script is executed directly
if (import.meta.url === `file://${process.argv[1]}`) {
importAllLorcana()
.then(() => {
console.log('\n🎉 Lorcana import completed!');
process.exit(0);
})
.catch((error) => {
console.error('❌ Import failed:', error);
process.exit(1);
});
}
export { importAllLorcana, importLorcanaSet };