-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
562 lines (490 loc) · 24.7 KB
/
script.js
File metadata and controls
562 lines (490 loc) · 24.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
const uploadZone = document.getElementById('uploadZone');
const fileInput = document.getElementById('fileInput');
const modList = document.getElementById('modList');
let testList = [];
// --- Utilities ---
function normalize(name) { return name.toLowerCase().replace(/[^a-z0-9]/g, ''); }
function extractModName(f) {
return f.replace(/\.jar$/i, '').replace(/\.disabled$/i, '')
.replace(/[-_+]\d+\.\d+.*$/i, '')
.replace(/[-](fabric|forge|neoforge|quilt)$/i, '').trim();
}
// Improved Regex for Filenames
function extractVersionFromFilename(str, extractMC = false) {
if (extractMC) {
// Matches "1.20", "1.20.1"
const mcVerMatch = str.match(/1\.\d+(\.\d+)?/);
return mcVerMatch ? mcVerMatch[0] : 'Unknown';
}
// Matches "-v1.0.0", "-1.0.0", " 1.0.0", "+1.20.1"
const verMatch = str.match(/[-_ +]v?(\d+\.\d+(?:\.\d+)?)/);
return verMatch ? verMatch[1] : 'Unknown';
}
function setStep(stepNum) {
const s1 = document.querySelector('#step1 .circle'), s2 = document.querySelector('#step2 .circle'), s3 = document.querySelector('#step3 .circle');
const l1 = document.getElementById('line1'), l2 = document.getElementById('line2');
[s1, s2, s3].forEach(s => { if(s) s.classList.remove('active', 'completed'); });
[l1, l2].forEach(l => { if(l) l.classList.remove('completed'); });
if (stepNum >= 1 && s1) s1.classList.add('active');
if (stepNum >= 2) {
if(s1) s1.classList.add('completed');
if(l1) l1.classList.add('completed');
if(s2) s2.classList.add('active');
}
if (stepNum >= 3) {
if(s2) s2.classList.add('completed');
if(l2) l2.classList.add('completed');
if(s3) s3.classList.add('completed');
}
}
// --- Events ---
uploadZone.addEventListener('dragover', (e) => { e.preventDefault(); uploadZone.classList.add('dragover'); });
uploadZone.addEventListener('dragleave', () => { uploadZone.classList.remove('dragover'); });
uploadZone.addEventListener('drop', (e) => {
e.preventDefault();
uploadZone.classList.remove('dragover');
const file = e.dataTransfer.files[0];
if (file) processFile(file);
});
fileInput.addEventListener('change', (e) => { if (e.target.files[0]) processFile(e.target.files[0]); });
// --- FILE PROCESSING ---
async function processFile(file) {
let mods = [];
let mcVersion = 'Unknown', loaderType = 'Unknown';
setStep(1);
try {
if (file.name.endsWith('.mrpack')) {
const zip = await JSZip.loadAsync(file);
const json = JSON.parse(await zip.file('modrinth.index.json').async('string'));
mcVersion = json.dependencies?.minecraft || 'Unknown';
const lKey = Object.keys(json.dependencies || {}).find(k => ['fabric','forge','neoforge','quilt'].some(l => k.includes(l)));
loaderType = lKey ? lKey.charAt(0).toUpperCase() + lKey.slice(1) : 'Unknown';
mods = json.files.map(f => {
const fileName = f.path.split('/').pop();
return {
name: extractModName(fileName),
id: null,
version: extractVersionFromFilename(fileName),
mcTarget: mcVersion,
detectedLoader: loaderType,
enabled: !f.path.includes('.disabled'),
source: 'mrpack'
};
});
}
else if (file.name.endsWith('.jar')) {
const meta = await extractJarMetadata(file);
mods = [meta];
loaderType = meta.detectedLoader !== 'Unknown' ? meta.detectedLoader : 'Unknown';
}
else if (file.name.endsWith('.txt')) {
const text = await file.text();
const info = await showVersionDialog();
if (info) {
mcVersion = info.mcVersion;
loaderType = info.loaderType;
}
mods = text.split('\n').filter(l => l.trim() && !l.startsWith('#')).map(l => {
const line = l.trim();
return {
name: extractModName(line),
id: extractModName(line),
version: extractVersionFromFilename(line),
mcTarget: mcVersion,
detectedLoader: loaderType,
enabled: true,
source: 'text'
};
});
}
const enabledMods = mods.filter(m => m.enabled);
document.getElementById('fileName').textContent = file.name;
if(mcVersion !== 'Unknown') document.getElementById('mcVersion').textContent = mcVersion;
if(loaderType !== 'Unknown') document.getElementById('loaderType').textContent = loaderType;
document.getElementById('modCount').textContent = `${enabledMods.length} total`;
modList.innerHTML = mods.map(m => {
const showLoader = m.detectedLoader && m.detectedLoader !== 'Unknown' && m.detectedLoader !== 'undefined';
return `
<div class="mod-item ${m.enabled ? '' : 'disabled'}" title="ID: ${m.id || '?'} | Ver: ${m.version} | MC: ${m.mcTarget}">
<div style="overflow:hidden;">
<span class="mod-name">
${m.name || m.id}
<span style="font-weight:normal; opacity:0.7; font-size: 0.9em; margin-left: 5px;">
${m.version !== 'Unknown' ? `v${m.version}` : ''}
</span>
</span>
<div style="font-size:0.75rem; color:#888;">
${m.mcTarget !== 'Unknown' ? `Target: MC ${m.mcTarget}` : 'Unknown MC Ver'}
${showLoader ? `(${m.detectedLoader})` : ''}
</div>
</div>
<span class="mod-status ${m.enabled ? 'status-enabled' : 'status-disabled'}">${m.enabled ? 'Enabled' : 'Disabled'}</span>
</div>`
}).join('');
setStep(2);
await runDeepSeekAnalysis(enabledMods, mcVersion, loaderType);
setStep(3);
} catch (e) {
console.error(e);
setStep(1);
alert("Error processing file: " + e.message);
}
}
// --- ROBUST JAR EXTRACTOR (With SMART EXTRACTION RESTORED) ---
async function extractJarMetadata(file) {
try {
const zip = await JSZip.loadAsync(file);
let meta = {
name: file.name,
id: null,
version: 'Unknown',
mcTarget: 'Unknown',
detectedLoader: 'Unknown',
dependencies: [],
enabled: true
};
// 1. FABRIC / QUILT
const fabricFile = zip.file('fabric.mod.json') || zip.file('quilt.mod.json');
if (fabricFile) {
try {
const content = await fabricFile.async('string');
// CLEANER: Removes comments but preserves URLs
const cleaned = content.replace(/(".*?"|'.*?')|(\/\/.*$|\/\*[\s\S]*?\*\/)/gm, (m, group1) => group1 || "");
const json = JSON.parse(cleaned);
meta.id = json.id;
meta.name = json.name || json.id;
meta.version = json.version;
meta.detectedLoader = 'Fabric';
meta.dependencies = json.depends ? Object.keys(json.depends) : [];
// STRATEGY A: Check 'depends' block (Standard)
if (json.depends && json.depends.minecraft) {
const rawMc = json.depends.minecraft;
const mcString = Array.isArray(rawMc) ? rawMc[0] : rawMc;
if (typeof mcString === 'string') {
meta.mcTarget = mcString.replace(/[<>=^~]/g, '').split(' ')[0];
}
}
// STRATEGY B: Check Version String (e.g., "0.3.5+1.20.1")
// --- RESTORED FEATURE ---
if (meta.mcTarget === 'Unknown' && json.version && json.version.includes('+')) {
const parts = json.version.split('+');
if (parts[1] && parts[1].match(/^1\.\d+/)) {
meta.mcTarget = parts[1];
}
}
} catch (err) {
console.warn("Fabric JSON parse error", err);
}
}
// 2. FORGE / NEOFORGE
const forgeFile = zip.file('META-INF/mods.toml');
if (forgeFile) {
try {
const content = await forgeFile.async('string');
const modIdMatch = content.match(/modId\s*=\s*["'](.*?)["']/);
const displayNameMatch = content.match(/displayName\s*=\s*["'](.*?)["']/);
const versionMatch = content.match(/version\s*=\s*["'](.*?)["']/);
meta.id = modIdMatch ? modIdMatch[1] : null;
meta.name = displayNameMatch ? displayNameMatch[1] : (meta.id || file.name);
const rawVer = versionMatch ? versionMatch[1] : 'Unknown';
meta.version = rawVer.includes('$') ? extractVersionFromFilename(file.name) : rawVer;
meta.detectedLoader = 'Forge';
// Try TOML regex
const mcDepMatch = content.match(/modId\s*=\s*["']minecraft["'][\s\S]*?versionRange\s*=\s*["'](.*?)["']/);
if (mcDepMatch) {
meta.mcTarget = mcDepMatch[1].replace(/[\[\]\(\),<>=]/g, ' ').trim().split(' ')[0];
}
} catch (err) {}
}
// 3. FINAL FALLBACK (Filename guessing)
if (meta.mcTarget === 'Unknown') meta.mcTarget = extractVersionFromFilename(file.name, true);
if (!meta.name || meta.name === file.name) meta.name = extractModName(file.name);
if (meta.version === 'Unknown') meta.version = extractVersionFromFilename(file.name);
if (meta.detectedLoader === 'Unknown') {
if (file.name.toLowerCase().includes('fabric')) meta.detectedLoader = 'Fabric';
else if (file.name.toLowerCase().includes('forge')) meta.detectedLoader = 'Forge';
else if (file.name.toLowerCase().includes('neoforge')) meta.detectedLoader = 'NeoForge';
}
return meta;
} catch (e) {
console.warn("Jar Error:", file.name, e);
const guessLoader = file.name.toLowerCase().includes('forge') ? 'Forge' :
(file.name.toLowerCase().includes('fabric') ? 'Fabric' : 'Unknown');
return {
name: extractModName(file.name),
version: extractVersionFromFilename(file.name),
mcTarget: extractVersionFromFilename(file.name, true),
detectedLoader: guessLoader,
enabled: true
};
}
}
async function runDeepSeekAnalysis(modListObjects, mcVersion, loader) {
const resultsContainer = document.querySelector('.results-scroll');
resultsContainer.innerHTML = createThinkingUI();
// PAYLOAD: Send full version string to AI
const finalPayload = {
mcVersion,
loader,
mods: modListObjects.map(m => ({
name: `${m.name} - v${m.version}${m.mcTarget !== 'Unknown' ? ` (MC ${m.mcTarget})` : ''}`,
id: m.id,
version: m.version,
loader: m.detectedLoader,
dependencies: m.dependencies
}))
};
testList.forEach(tm => {
finalPayload.mods.push({ name: tm.name, source: 'search', version: 'Unknown' });
});
await performAnalysis(finalPayload, resultsContainer);
}
// --- STREAMING & API ---
function createThinkingUI() {
return `
<div class="reasoning-accordion">
<div class="reasoning-header" onclick="this.parentElement.classList.toggle('open')">
<span><span class="reasoning-icon">🧠</span> DeepSeek Thoughts</span>
<span class="arrow">▼</span>
</div>
<div class="reasoning-content" id="liveReasoningOutput">Initializing stream...</div>
</div>
<div id="visualizationMessageContainer"></div>
<div id="finalAnalysisOutput"></div>
`;
}
async function performAnalysis(payload, container) {
const useServer = document.getElementById('useServerKey').checked;
const response = await fetch('/api/analyze', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Custom-API-Key': document.getElementById('customApiKey').value
},
body: JSON.stringify({ ...payload, useCustomKey: !useServer })
});
if (!response.ok) throw new Error("API Response Error");
const reader = response.body.getReader();
const decoder = new TextDecoder();
const reasoningEl = document.getElementById('liveReasoningOutput');
let fullFinalContent = "";
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop();
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed || trimmed === 'data: [DONE]') continue;
if (trimmed.startsWith('data: ')) {
try {
const json = JSON.parse(trimmed.slice(6));
const delta = json.choices[0].delta;
if (delta.reasoning_content) {
reasoningEl.textContent += delta.reasoning_content;
reasoningEl.scrollTop = reasoningEl.scrollHeight;
}
if (delta.content) fullFinalContent += delta.content;
} catch (err) {}
}
}
}
document.querySelector('.reasoning-accordion').classList.remove('open');
const visContainer = document.getElementById('visualizationMessageContainer');
if (visContainer) {
visContainer.innerHTML = `
<div style="text-align: center; color: #2e7d32; font-style: italic; margin: 15px 0 25px; font-weight: 500; animation: fadeIn 0.5s;">
✨ Creating visualization of gathered information...
</div>`;
}
const outputDiv = document.getElementById('finalAnalysisOutput');
if (outputDiv) {
await renderResultsToTarget(fullFinalContent, outputDiv);
}
}
async function renderResultsToTarget(text, container) {
container.innerHTML = '';
const incompatibleBlocks = [...text.matchAll(/\[INCOMPATIBLE_MOD\]([\s\S]*?)\[\/INCOMPATIBLE_MOD\]/g)];
if (incompatibleBlocks.length > 0) {
let html = '<div class="advice-section"><h3>⚠️ Incompatible Mods</h3>';
for (const b of incompatibleBlocks) {
const inner = b[1];
const idRaw = inner.match(/ID:\s*(.+)/i)?.[1]?.trim() || 'Unknown Mod';
const nameForSearch = idRaw.split(' -')[0].split('(')[0].trim();
const issue = inner.match(/ISSUE:\s*([\s\S]*?)(?=FIX:|$)/i)?.[1]?.trim() || '';
const fix = inner.match(/FIX:\s*([\s\S]*?)$/i)?.[1]?.trim() || '';
const mData = await fetchModrinthData(nameForSearch);
html += `
<div class="advice-card incompatible">
<div class="advice-header" style="display: flex; align-items: center; gap: 10px; color: #d32f2f; margin-bottom: 10px;">
${mData.icon ? `<img src="${mData.icon}" style="width:32px; height:32px; border-radius:8px;">` : '🧩'}
<h4 style="margin:0;">${idRaw}</h4>
</div>
<div class="sub-item" style="border-left: 4px solid #d32f2f; background: #fff5f5; padding: 12px; border-radius: 8px;">
<p style="margin: 0 0 5px 0;"><strong>Issue:</strong> ${issue}</p>
<p style="margin: 0;"><strong>Fix:</strong> ${fix}</p>
</div>
</div>`;
await new Promise(r => setTimeout(r, 20));
}
container.innerHTML += html + '</div>';
}
const sections = text.split(/(?=###|##|Performance Optimization|General Recommendations|MISSING DEPENDENCY)/g);
sections.forEach(sec => {
const cleanSec = sec.replace(/^#+\s*/, '').trim();
if (!cleanSec || cleanSec.includes('[INCOMPATIBLE_MOD]')) return;
const lines = cleanSec.split('\n');
const title = lines[0]
.replace(/\*\*/g, '')
.replace(/:+$/, '')
.trim();
let sectionHtml = `<div class="advice-card"><div class="advice-header" style="display: flex; align-items: center; gap: 8px;"><span style="font-size: 1.2rem;">💡</span><h3>${title}</h3></div><div class="advice-content">`;
let hasContent = false;
lines.slice(1).forEach(line => {
const subMatch = line.trim().match(/^[\-\*]?\s?\*\*(.*?)\*\*[:\s]*(.*)/);
if (subMatch) {
hasContent = true;
sectionHtml += `<div class="sub-item"><strong style="display:block; color:#1b5e20;">${subMatch[1]}</strong><p>${subMatch[2]}</p></div>`;
} else if (line.trim().length > 3) {
hasContent = true;
sectionHtml += `<p style="margin: 8px 0 8px 15px;">
${
line
.trim()
.replace(/\*\*/g,'')
.replace(/^[\-\*]\s?/, '')
}
</p>`;
}
});
sectionHtml += `</div></div>`;
if (hasContent) container.innerHTML += sectionHtml;
});
}
// --- Search & Add Logic ---
document.getElementById('searchBtn').addEventListener('click', async () => {
const query = document.getElementById('modSearchInput').value.trim();
const rawMcV = document.getElementById('mcVersion').textContent.trim();
const rawLoader = document.getElementById('loaderType').textContent.trim();
const mcV = rawMcV === '--' ? 'Unknown' : rawMcV;
const loader = rawLoader.toLowerCase().replace('-loader', '').trim();
if (!query || mcV === 'Unknown') return alert("Please upload a modpack first!");
const resultsContainer = document.getElementById('searchResultList');
resultsContainer.innerHTML = '<p>Searching...</p>';
try {
const facets = `[["versions:${mcV}"],["categories:${loader}"]]`;
const mrUrl = `https://api.modrinth.com/v2/search?query=${encodeURIComponent(query)}&facets=${encodeURIComponent(facets)}`;
const mrReq = fetch(mrUrl).then(res => res.json());
const cfUrl = `/api/search?q=${encodeURIComponent(query)}&mc=${mcV}&loader=${loader}`;
const cfReq = fetch(cfUrl).then(res => res.json());
const [mrData, cfData] = await Promise.all([mrReq, cfReq]);
const combinedHits = [
...(mrData.hits || []).map(h => ({ title: h.title, source: 'Modrinth', icon: h.icon_url || '' })),
...(cfData.data || []).map(h => ({ title: h.name, source: 'CurseForge', icon: h.logo ? h.logo.thumbnailUrl : '' }))
];
resultsContainer.innerHTML = combinedHits.map(h => `
<div class="search-item" style="min-width: 250px;">
<div class="mod-info" style="display: flex; align-items: center; gap: 12px;">
<img src="${h.icon}" onerror="this.src='https://placehold.co/32?text=?'" style="width:36px; height:36px; border-radius:8px; object-fit: cover;">
<div><strong style="display:block;">${h.title}</strong><small style="color:#888">${h.source}</small></div>
</div>
<button class="btn-toggle btn-add" onclick="manageTestList('${h.title.replace(/'/g, "\\'")}', true, '${h.icon}')">+</button>
</div>`).join('');
} catch (e) { resultsContainer.innerHTML = `<p>Search failed: ${e.message}</p>`; }
});
window.manageTestList = function(name, add, icon) {
if (add) { if (!testList.some(m => m.name === name)) testList.push({ name, icon }); }
else { testList = testList.filter(m => m.name !== name); }
const addedListEl = document.getElementById('addedModsList');
if (testList.length === 0) addedListEl.innerHTML = `<div class="empty-msg">No mods added yet. Search above and click + to add.</div>`;
else {
addedListEl.innerHTML = testList.map(m => `
<div class="search-item">
<div style="display: flex; align-items: center; gap: 10px;">
<img src="${m.icon}" onerror="this.src='https://placehold.co/24?text=?'" style="width:24px; height:24px; border-radius:4px;">
<span>${m.name}</span>
</div>
<button class="btn-toggle btn-remove" onclick="manageTestList('${m.name.replace(/'/g, "\\'")}', false)">-</button>
</div>`).join('');
}
document.getElementById('checkCompatibilityBtn').classList.toggle('hidden', testList.length === 0);
};
// --- CHECK COMPATIBILITY BUTTON ---
document.getElementById('checkCompatibilityBtn').addEventListener('click', async () => {
// 1. Define Button first
const btn = document.getElementById('checkCompatibilityBtn');
// 2. Lock
if (btn.disabled) return;
btn.disabled = true;
const originalText = btn.textContent;
btn.textContent = "Analyzing...";
btn.style.opacity = "0.7";
const bar = document.querySelector('.status-bar-container');
const progress = document.querySelector('.status-progress');
const resultsContainer = document.querySelector('.results-scroll');
if (bar) bar.style.display = 'block';
if (progress) progress.style.width = '20%';
// 3. Define payload
const mcV = document.getElementById('mcVersion').textContent.trim();
const loader = document.getElementById('loaderType').textContent.trim();
const uploadedElements = Array.from(document.querySelectorAll('#modList .mod-item'));
const modsPayload = uploadedElements.map(el => {
const name = el.querySelector('.mod-name').innerText.split('\n')[0].trim();
const tooltip = el.title;
const idMatch = tooltip.match(/ID: (.*?) \|/);
const verMatch = tooltip.match(/Ver: (.*?) \|/);
const mcMatch = tooltip.match(/MC: (.*?)$/);
const cleanVer = verMatch ? verMatch[1].trim() : 'Unknown';
const cleanMC = mcMatch ? mcMatch[1].trim() : 'Unknown';
return {
name: `${name} - ${cleanVer}${cleanMC !== 'Unknown' ? ` (MC ${cleanMC})` : ''}`,
id: idMatch ? idMatch[1] : null,
version: cleanVer,
source: 'ui_scrape'
};
});
testList.forEach(tm => {
if (!modsPayload.some(m => m.name.startsWith(tm.name))) {
modsPayload.push({ name: tm.name, source: 'search', version: 'Unknown' });
}
});
const payload = { mcVersion: mcV, loader: loader, mods: modsPayload };
// 4. UI Setup
resultsContainer.innerHTML = createThinkingUI();
const reasoningBox = document.getElementById('liveReasoningOutput');
if(reasoningBox) reasoningBox.textContent = "Analyzing combined compatibility...";
// 5. Run
try {
if (progress) progress.style.width = '40%';
await performAnalysis(payload, resultsContainer);
if (progress) progress.style.width = '100%';
} catch (e) {
console.error(e);
resultsContainer.innerHTML = `<div class="status-message error"><p>Analysis failed: ${e.message}</p></div>`;
} finally {
setTimeout(() => { if (bar) bar.style.display = 'none'; }, 1000);
btn.disabled = false;
btn.textContent = originalText;
btn.style.opacity = "1";
}
});
async function fetchModrinthData(n) {
try {
const r = await fetch(`https://api.modrinth.com/v2/search?query=${encodeURIComponent(n)}&limit=1`);
const d = await r.json();
return { icon: d.hits?.[0]?.icon_url, url: d.hits?.[0]?.slug };
} catch { return { icon: null, url: null }; }
}
function showVersionDialog() {
return new Promise((resolve) => {
const d = document.createElement('div');
d.className = 'version-dialog-overlay';
d.innerHTML = `<div class="version-dialog"><h3>Modpack Info</h3><input type="text" id="vIn" placeholder="1.20.1"><select id="lIn"><option value="Fabric">Fabric</option><option value="Forge">Forge</option><option value="NeoForge">NeoForge</option><option value="Quilt">Quilt</option></select><div class="version-dialog-footer"><button id="cancelBtn">Cancel</button><button id="confirmBtn">Confirm</button></div></div>`;
document.body.appendChild(d);
const v = d.querySelector('#vIn'), l = d.querySelector('#lIn');
d.querySelector('#confirmBtn').onclick = () => { if (v.value && l.value) { document.body.removeChild(d); resolve({ mcVersion: v.value, loaderType: l.value }); } };
d.querySelector('#cancelBtn').onclick = () => { document.body.removeChild(d); resolve(null); };
});
}