-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodedost.js
More file actions
2155 lines (1928 loc) · 72.8 KB
/
codedost.js
File metadata and controls
2155 lines (1928 loc) · 72.8 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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const BACKEND_URL = 'https://codedost-backend-production.up.railway.app';
async function checkQuota() {
try {
const r = await fetch(`${BACKEND_URL}/api/analyze/quota`, {
credentials: 'include'
});
if (!r.ok) return { allowed: true }; // if backend down, allow anyway
return await r.json();
} catch {
return { allowed: true }; // if backend unreachable, allow anyway
}
}
async function incrementQuota() {
try {
await fetch(`${BACKEND_URL}/api/analyze/increment`, {
method: 'POST',
credentials: 'include'
});
} catch {}
}
// ═══════════════════════════════════════
// AUTH SYSTEM
// ═══════════════════════════════════════
let authToken = localStorage.getItem('cd_auth_token') || null;
let currentUser = JSON.parse(localStorage.getItem('cd_user') || 'null');
function openAuthModal() {
if (currentUser) {
// Already logged in — show logout option
if (confirm(`Logged in as ${currentUser.email}\n\nLogout karna hai?`)) {
logoutUser();
}
return;
}
document.getElementById('auth-modal-overlay').style.display = 'flex';
}
function closeAuthModalOutside(e) {
if (e.target === document.getElementById('auth-modal-overlay')) {
document.getElementById('auth-modal-overlay').style.display = 'none';
}
}
function switchAuthTab(tab) {
document.getElementById('auth-form-login').style.display = tab === 'login' ? 'block' : 'none';
document.getElementById('auth-form-register').style.display = tab === 'register' ? 'block' : 'none';
document.getElementById('auth-tab-login').classList.toggle('active-tab', tab === 'login');
document.getElementById('auth-tab-register').classList.toggle('active-tab', tab === 'register');
document.getElementById('auth-submit-btn').textContent = tab === 'login' ? 'Login' : 'Sign Up';
document.getElementById('auth-modal-title').textContent = tab === 'login' ? '👤 Login to CodeDost' : '👤 Sign Up — It\'s Free';
document.getElementById('auth-error-msg').style.display = 'none';
}
async function submitAuth() {
const isLogin = document.getElementById('auth-form-login').style.display !== 'none';
const btn = document.getElementById('auth-submit-btn');
const errEl = document.getElementById('auth-error-msg');
errEl.style.display = 'none';
btn.disabled = true;
btn.textContent = 'Please wait...';
try {
let body, endpoint;
if (isLogin) {
endpoint = '/api/auth/login';
body = {
email: document.getElementById('auth-email-login').value.trim(),
password: document.getElementById('auth-pass-login').value,
};
} else {
endpoint = '/api/auth/register';
body = {
name: document.getElementById('auth-name-register').value.trim(),
email: document.getElementById('auth-email-register').value.trim(),
password: document.getElementById('auth-pass-register').value,
};
}
const res = await fetch(BACKEND_URL + endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify(body),
});
const data = await res.json();
console.log(data)
if (!res.ok) {
const errEl = document.getElementById('auth-error-msg');
errEl.style.display = 'block';
let messages = [];
if (data.errors && Array.isArray(data.errors)) {
messages = data.errors.map(err => err.message);
}
else if (data.error) {
messages.push(data.error);
}
else if (data.message) {
messages.push(data.message);
}
else {
messages.push('Something went wrong');
}
errEl.innerHTML = messages.map(msg => `• ${msg}`).join('<br>');
return;
}
if(data.success === false){
console.log(data.message)
let auth= document.getElementById('auth-error-msg')
auth.innerText=data.message
auth.style.display='block'
}
// Save token and user
authToken = data.token || data.accessToken;
currentUser = data.user;
localStorage.setItem('cd_auth_token', authToken);
localStorage.setItem('cd_user', JSON.stringify(currentUser));
document.getElementById('auth-modal-overlay').style.display = 'none';
updateAuthUI();
loadQuotaFromBackend();
showToast('success', `Welcome ${currentUser.name || currentUser.email}! 🎉`);
} catch (err) {
// console.log(err)
} finally {
btn.disabled = false;
btn.textContent = isLogin ? 'Login' : 'Sign Up';
}
}
function logoutUser() {
authToken = null;
currentUser = null;
localStorage.removeItem('cd_auth_token');
localStorage.removeItem('cd_user');
updateAuthUI();
showToast('success', 'Logged out!');
}
function updateAuthUI() {
const btn = document.getElementById('auth-btn');
const quotaPill = document.getElementById('quota-pill');
if (currentUser) {
btn.textContent = `👤 ${currentUser.name || currentUser.email.split('@')[0]}`;
btn.style.background = 'var(--green)';
quotaPill.style.display = 'flex';
} else {
btn.textContent = '👤 Login / Sign Up';
btn.style.background = 'var(--purple)';
quotaPill.style.display = 'none';
}
}
// ═══════════════════════════════════════════
// AUTH MODAL: Forgot Password & Reset Password
// ═══════════════════════════════════════════
let authMode = 'login'; // login | register | forgot | reset
function switchAuthTab(tab) {
authMode = tab;
// Hide all forms
document.getElementById('auth-form-login').style.display = 'none';
document.getElementById('auth-form-register').style.display = 'none';
document.getElementById('auth-form-forgot').style.display = 'none';
document.getElementById('auth-form-reset').style.display = 'none';
// Hide all tabs
document.getElementById('auth-tab-login').classList.remove('active-tab');
document.getElementById('auth-tab-register').classList.remove('active-tab');
document.getElementById('auth-tab-forgot').classList.remove('active-tab');
// Clear messages
document.getElementById('auth-error-msg').style.display = 'none';
document.getElementById('auth-success-msg').style.display = 'none';
const btn = document.getElementById('auth-submit-btn');
if (tab === 'login') {
document.getElementById('auth-form-login').style.display = 'block';
document.getElementById('auth-tab-login').classList.add('active-tab');
document.getElementById('auth-modal-title').textContent = '👤 Login to CodeDost';
btn.textContent = 'Login';
} else if (tab === 'register') {
document.getElementById('auth-form-register').style.display = 'block';
document.getElementById('auth-tab-register').classList.add('active-tab');
document.getElementById('auth-modal-title').textContent = '👤 Sign Up — It\'s Free';
btn.textContent = 'Sign Up';
} else if (tab === 'forgot') {
document.getElementById('auth-form-forgot').style.display = 'block';
document.getElementById('auth-tab-forgot').classList.add('active-tab');
document.getElementById('auth-modal-title').textContent = '🔑 Forgot Password?';
btn.textContent = 'Send Reset Link';
} else if (tab === 'reset') {
document.getElementById('auth-form-reset').style.display = 'block';
document.getElementById('auth-modal-title').textContent = '🔐 Reset Password';
btn.textContent = 'Reset Password';
}
}
async function submitAuth() {
const btn = document.getElementById('auth-submit-btn');
const errEl = document.getElementById('auth-error-msg');
const successEl = document.getElementById('auth-success-msg');
errEl.style.display = 'none';
successEl.style.display = 'none';
btn.disabled = true;
btn.textContent = 'Please wait...';
try {
if (authMode === 'login') {
await handleLoginNew();
} else if (authMode === 'register') {
await handleRegisterNew();
} else if (authMode === 'forgot') {
await handleForgotPassword();
} else if (authMode === 'reset') {
await handleResetPassword();
}
} finally {
btn.disabled = false;
btn.textContent = getButtonText();
}
}
function getButtonText() {
const texts = {
login: 'Login',
register: 'Sign Up',
forgot: 'Send Reset Link',
reset: 'Reset Password'
};
return texts[authMode] || 'Submit';
}
async function handleLoginNew() {
const email = document.getElementById('auth-email-login').value.trim();
const password = document.getElementById('auth-pass-login').value;
if (!email || !password) {
showAuthError('Email and password required.');
return;
}
const res = await fetch(`${BACKEND_URL}/api/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ email, password })
});
const data = await res.json();
if (!res.ok || !data.success) {
showAuthError(data.message || 'Login failed.');
return;
}
authToken = data.accessToken || data.token;
currentUser = data.user;
localStorage.setItem('cd_auth_token', authToken);
localStorage.setItem('cd_user', JSON.stringify(currentUser));
showAuthSuccess(`Welcome ${currentUser.name}! 🎉`);
updateAuthUI();
loadQuotaFromBackend();
setTimeout(() => {
document.getElementById('auth-modal-overlay').style.display = 'none';
}, 1500);
}
async function handleRegisterNew() {
const name = document.getElementById('auth-name-register').value.trim();
const email = document.getElementById('auth-email-register').value.trim();
const password = document.getElementById('auth-pass-register').value;
const university = document.getElementById('auth-university-register').value.trim();
if (!name || !email || !password) {
showAuthError('Name, email, and password required.');
return;
}
if (password.length < 8) {
showAuthError('Password must be at least 8 characters.');
return;
}
console.log(({ name, email, password, university }))
const res = await fetch(`${BACKEND_URL}/api/auth/register`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ name, email, password, university })
});
console.log(res)
const data = await res.json();
console.log(data)
if (!res.ok || !data.success) {
showAuthError(data.message || 'Registration failed.');
return;
}
authToken = data.accessToken || data.token;
currentUser = data.user;
localStorage.setItem('cd_auth_token', authToken);
localStorage.setItem('cd_user', JSON.stringify(currentUser));
showAuthSuccess('✅ Account created! Check email for verification link.');
updateAuthUI();
// Clear form
document.getElementById('auth-name-register').value = '';
document.getElementById('auth-email-register').value = '';
document.getElementById('auth-pass-register').value = '';
document.getElementById('auth-university-register').value = '';
setTimeout(() => {
document.getElementById('auth-modal-overlay').style.display = 'none';
}, 2500);
}
async function handleForgotPassword() {
const email = document.getElementById('auth-email-forgot').value.trim();
if (!email) {
showAuthError('Please enter your email address.');
return;
}
const res = await fetch(`${BACKEND_URL}/api/auth/forgot-password`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ email })
});
const data = await res.json();
if (!data.success) {
showAuthError(data.message || 'Failed to send reset link.');
return;
}
showAuthSuccess('✅ Reset link sent! Check your email inbox.');
document.getElementById('auth-email-forgot').value = '';
setTimeout(() => {
document.getElementById('auth-modal-overlay').style.display = 'none';
}, 2000);
}
async function handleResetPassword() {
const newPassword = document.getElementById('auth-pass-reset-new').value;
const confirmPassword = document.getElementById('auth-pass-reset-confirm').value;
if (!newPassword || !confirmPassword) {
showAuthError('Please enter both passwords.');
return;
}
if (newPassword.length < 8) {
showAuthError('Password must be at least 8 characters.');
return;
}
if (newPassword !== confirmPassword) {
showAuthError('Passwords do not match.');
return;
}
// Get token from URL if available
const params = new URLSearchParams(window.location.search);
const token = params.get('reset_token');
if (!token) {
showAuthError('Invalid reset link. Please request a new one.');
return;
}
const res = await fetch(`${BACKEND_URL}/api/auth/reset-password`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ token, newPassword, confirmPassword })
});
const data = await res.json();
if (!data.success) {
showAuthError(data.message || 'Password reset failed.');
return;
}
showAuthSuccess('✅ Password reset successfully! You can now login.');
// Clear form
document.getElementById('auth-pass-reset-new').value = '';
document.getElementById('auth-pass-reset-confirm').value = '';
setTimeout(() => {
switchAuthTab('login');
window.location.href = 'codedost.html'; // Remove token from URL
}, 2000);
}
function showAuthError(message) {
const el = document.getElementById('auth-error-msg');
el.textContent = '❌ ' + message;
el.style.display = 'block';
}
function showAuthSuccess(message) {
const el = document.getElementById('auth-success-msg');
el.textContent = message;
el.style.display = 'block';
}
async function loadQuotaFromBackend() {
if (!authToken) return;
try {
const r = await fetch(`${BACKEND_URL}/api/analyze/quota`, {
credentials: 'include',
headers: { Authorization: `Bearer ${authToken}` },
});
if (!r.ok) return;
const data = await r.json();
if (data.used !== undefined) {
document.getElementById('quota-used').textContent = data.used;
document.getElementById('quota-limit').textContent = data.limit || 20;
}
} catch {}
}
// ═══════════════════════════════════════
// STATE
// ═══════════════════════════════════════
let currentMode = "urdu"; // urdu | mixed | english
let currentLang = "python";
let sessionHistory = JSON.parse(localStorage.getItem("cd_history") || "[]");
let mistakePatterns = JSON.parse(localStorage.getItem("cd_patterns") || "{}");
const LANG_TAGS = {
python: "script.py",
javascript: "app.js",
java: "Main.java",
cpp: "main.cpp",
html: "index.html",
sql: "query.sql",
};
// ═══════════════════════════════════════
// SYSTEM PROMPT — THE HEART OF CODEDOST
// ═══════════════════════════════════════
function buildSystemPrompt() {
const modeInstructions = {
urdu: `You MUST respond primarily in Roman Urdu (Urdu written in English letters) mixed with essential English technical terms. This is how Pakistani CS students naturally talk: "is error ka matlab hai ke..." or "Dekhen, ap ne yahan variable declare nahi kiya..." Keep Urdu dominant (70%) with English technical words (30%).`,
mixed: `Respond in a 50/50 mix of Roman Urdu and English. Switch naturally between both as Pakistani developers do in real life.`,
english: `Respond entirely in clear, simple English. Respectful and encouraging tone, like a senior developer helping a junior.`,
};
return `You are CodeDost, a warm, encouraging AI coding tutor for Pakistani university students. You explain code errors in a Respectful friendly, big-brother/Friend style — never condescending.
LANGUAGE INSTRUCTION: ${modeInstructions[currentMode]}
CRITICAL: You MUST respond with ONLY a valid JSON object. No text before or after. No markdown code fences. No explanation outside the JSON. Just the raw JSON object.
JSON FORMAT (fill every field):
{
"error_type": "Short name of the error (e.g. SyntaxError, TypeError, LogicError, UndefinedVariable, IndexError, NullReference, AsyncError, ImportError)",
"severity": "beginner OR intermediate OR advanced",
"plain_explanation": "2-3 sentences explaining WHY this error happened in ${currentMode === "english" ? "simple English" : "Roman Urdu mixed with English technical terms"}.Make it conversational.",
"desi_analogy": "A relatable Pakistani everyday analogy that explains the concept. Use best and most perfect daily life examples most suitable and valid one not a dumb one like just for fromality Format: '${currentMode !== "english" ? "Sunaien: [analogy in Roman Urdu]" : "Think of it like: [analogy]"}'",
"fixed_code": "The complete corrected code. Keep same structure, just fix the bug(s). No markdown backticks.",
"fix_bullets": [
"First change kya kiya aur kyun (in ${currentMode === "english" ? "English" : "Roman Urdu"})",
"Second change if any",
"Third change if any"
],
"concept_to_study": "The one CS concept this error reveals a gap in (e.g. 'Variable Scope', 'Data Types', 'Array Indexing', 'Async/Await', 'OOP Inheritance', 'Error Handling')",
"concept_why": "${currentMode !== "english" ? "Is concept ko samjhoge toh aisi galtiyan nahi hongi" : "Understanding this will prevent similar bugs"}",
"concept_search": "Exact YouTube/Google search query to learn this concept (e.g. 'Python list indexing tutorial for beginners')",
"mistake_category": "ONE of these exact strings: syntax_error, logic_error, type_error, null_reference, scope_error, async_error, import_error, index_error, other"
}
IMPORTANT RULES:
1. ALWAYS produce valid JSON — no trailing commas, no unescaped quotes in strings
2. fixed_code must be complete and runnable — not just the changed lines
3. desi_analogy must be genuinely relatable to a Pakistani student's daily life
4. Be encouraging — add a small motivational note in plain_explanation like "(Ye common mistake hai, ghhabrao mat!)"
5. fix_bullets should have 2-4 items minimum`;
}
// ═══════════════════════════════════════
// EXAMPLE SNIPPETS
// ═══════════════════════════════════════
const EXAMPLES = {
syntax: {
lang: "python",
code: `def calculate_total(items):
total = 0
for item in items
total += item['price']
return total
result = calculate_total([{'price': 100}, {'price': 250}])
print(result)`,
error: `SyntaxError: expected ':' (line 3)`,
},
typeerror: {
lang: "python",
code: `def get_username(user):
name = user['name']
upper_name = name.upper()
return "Hello " + upper_name + " your age is " + user['age']
print(get_username({'name': 'Ali', 'age': 21}))`,
error: `TypeError: can only concatenate str (not "int") to str`,
},
index: {
lang: "python",
code: `students = ['Ahmed', 'Sara', 'Bilal', 'Fatima']
for i in range(len(students) + 1):
print(f"Student {i+1}: {students[i]}")`,
error: `IndexError: list index out of range`,
},
undefined: {
lang: "javascript",
code: `function calculateDiscount(price) {
let discountRate = 0.1;
if (price > 1000) {
let discountRate = 0.2;
}
return price - (price * discountRate);
}
console.log(calculateDiscount(1500));`,
error: `Expected: 300 discount, Got: 150 discount (wrong result)`,
},
async: {
lang: "javascript",
code: `function getUserData(userId) {
const response = fetch(\`https://api.example.com/users/\${userId}\`);
const data = response.json();
return data.name;
}
const name = getUserData(123);
console.log("User:", name);`,
error: `TypeError: response.json is not a function (data shows [object Promise])`,
},
null: {
lang: "python",
code: `def find_student(students, name):
for student in students:
if student['name'] == name:
return student
# Function ends without returning anything
class_list = [{'name': 'Ahmed', 'grade': 'A'}, {'name': 'Sara', 'grade': 'B'}]
result = find_student(class_list, 'Usman')
print(result['grade'])`,
error: `TypeError: 'NoneType' object is not subscriptable`,
},
};
function loadExample(key) {
const ex = EXAMPLES[key];
if (!ex) return;
document.getElementById("code-input").value = ex.code;
document.getElementById("error-input").value = ex.error;
const picker = document.getElementById("lang-picker");
picker.value = ex.lang;
updateLang();
showToast("success", `Example loaded: ${key}`);
}
// Attach click listeners for example chips (decoupled from HTML inline handlers)
function initExampleChips() {
document.querySelectorAll(".example-chip").forEach((button) => {
button.addEventListener("click", () => {
loadExample(button.dataset.example);
});
});
}
// ═══════════════════════════════════════
// PROVIDER CONFIG
// ═══════════════════════════════════════
let currentProvider = localStorage.getItem("cd_provider") || "groq";
const PROVIDERS = {
groq: {
url: "https://api.groq.com/openai/v1/chat/completions",
model: "llama-3.3-70b-versatile",
header: (key) => ({
"Content-Type": "application/json",
Authorization: `Bearer ${key}`,
}),
keyPrefix: "gsk_",
storageKey: "cd_api_key_groq",
label: "Groq",
},
gemini: {
url: null, // handled separately via gemini REST
model: "gemini-1.5-flash",
header: (key) => ({ "Content-Type": "application/json" }),
keyPrefix: "AIza",
storageKey: "cd_api_key_gemini",
label: "Gemini",
},
openrouter: {
url: "https://openrouter.ai/api/v1/chat/completions",
model: "meta-llama/llama-3.1-8b-instruct:free",
header: (key) => ({
"Content-Type": "application/json",
Authorization: `Bearer ${key}`,
"HTTP-Referer": "https://codedost.app",
"X-Title": "CodeDost",
}),
keyPrefix: "sk-or-",
storageKey: "cd_api_key_openrouter",
label: "OpenRouter",
},
};
function getActiveKey() {
return localStorage.getItem(PROVIDERS[currentProvider].storageKey) || "";
}
// Utility: parse JSON robustly even with markdown/fence noise
function safeJSONParse(text) {
if (!text || typeof text !== "string") return null;
const cleaned = text
.replace(/^\s*```json\s*/i, "")
.replace(/^\s*```\s*/i, "")
.replace(/```\s*$/i, "")
.trim();
try {
return JSON.parse(cleaned);
} catch (err) {
// Fallback: find first JSON object substring
const match = cleaned.match(/\{[\s\S]*\}/);
if (!match) return null;
try {
return JSON.parse(match[0]);
} catch (innerErr) {
console.error("safeJSONParse failed", innerErr);
return null;
}
}
}
function validateResult(r) {
if (!r || typeof r !== "object") return false;
const required = [
"error_type",
"severity",
"plain_explanation",
"desi_analogy",
"fixed_code",
"fix_bullets",
"concept_to_study",
"concept_why",
"concept_search",
"mistake_category",
];
const hasAll = required.every((k) =>
Object.prototype.hasOwnProperty.call(r, k),
);
if (!hasAll) return false;
if (!Array.isArray(r.fix_bullets) || r.fix_bullets.length < 2) return false;
const severityValues = ["beginner", "intermediate", "advanced"];
if (!severityValues.includes(String(r.severity))) return false;
return true;
}
// ═══════════════════════════════════════
// MAIN ANALYZE FUNCTION
// ═══════════════════════════════════════
async function analyzeCode() {
const code = document.getElementById("code-input").value.trim();
const errorMsg = document.getElementById("error-input").value.trim();
if (!code) {
showToast("error", "Pehle code paste karo yaar!");
return;
}
// Check quota before proceeding
const quota = await checkQuota();
if (quota.allowed === false) {
showToast('error', `Monthly limit khatam — ${quota.used}/${quota.limit} analyses used`);
return;
}
const apiKey = getActiveKey();
if (!apiKey) {
showToast("error", "API key daalo pehle — upar wali button se");
openModal();
return;
}
const btn = document.getElementById("submit-btn");
btn.classList.add("loading");
btn.disabled = true;
try {
// Set up timeout controller (30 seconds)
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 30000);
const userMessage = `Language: ${currentLang.toUpperCase()}\n\nCode:\n${code}\n\n${errorMsg ? `Error Message: ${errorMsg}` : "(No error message — analyze the code for bugs)"}`;
let rawContent = "";
if (currentProvider === "gemini") {
// Gemini REST API (different format)
const gemUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=${apiKey}`;
const gemBody = {
contents: [
{
parts: [
{
text: buildSystemPrompt() + "\n\nUser request:\n" + userMessage,
},
],
},
],
generationConfig: { temperature: 0.4, maxOutputTokens: 1800 },
};
const res = await fetch(gemUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(gemBody),
signal: controller.signal,
});
if (!res.ok) {
const e = await res.json().catch(() => ({}));
throw new Error(e?.error?.message || `Gemini Error ${res.status}`);
}
const d = await res.json();
rawContent = d.candidates?.[0]?.content?.parts?.[0]?.text || "";
} else {
// OpenAI-compatible (Groq + OpenRouter)
const p = PROVIDERS[currentProvider];
const res = await fetch(p.url, {
method: "POST",
headers: p.header(apiKey),
body: JSON.stringify({
model: p.model,
max_tokens: 1800,
temperature: 0.4,
messages: [
{ role: "system", content: buildSystemPrompt() },
{ role: "user", content: userMessage },
],
}),
signal: controller.signal,
});
if (!res.ok) {
const e = await res.json().catch(() => ({}));
throw new Error(e?.error?.message || `API Error ${res.status}`);
}
const d = await res.json();
rawContent = d.choices?.[0]?.message?.content?.trim() || "";
}
// Clear timeout on success
clearTimeout(timeoutId);
// Parse JSON — strip any accidental markdown fences
const result = safeJSONParse(rawContent);
if (!result || !validateResult(result)) {
throw new Error("Invalid or malformed JSON response from model");
}
renderOutput(result, code, errorMsg);
saveToHistory(result, code, errorMsg);
updatePatterns(result.mistake_category, errorMsg, code);
showToast(
"success",
`Explanation ready! (via ${PROVIDERS[currentProvider].label})`,
);
await incrementQuota();
updateStreak();
incrementUsageCounter();
checkSimilarErrors(result.mistake_category);
} catch (err) {
console.error("CodeDost error:", err);
let msg = "Kuch error ho gaya. Dobara try karo.";
if (err.name === "AbortError")
msg = "Request timeout — 30 seconds se zyada laga. Dobara try karo.";
else if (err.message.includes("API key") || err.message.includes("401"))
msg = "API key galat hai. Check karo.";
else if (err.message.includes("quota") || err.message.includes("429")) {
startRateLimitCountdown(30);
return;
} else if (err.message.includes("JSON"))
msg = "Response parse nahi hua. Dobara try karo.";
else if (err.message.includes("fetch"))
msg = "Internet connection check karo.";
showToast("error", msg);
} finally {
btn.classList.remove("loading");
btn.disabled = false;
}
}
// ═══════════════════════════════════════
// RENDER OUTPUT
// ═══════════════════════════════════════
function renderOutput(r, originalCode, errorMsg) {
// Show output panel
document.getElementById("output-empty").style.display = "none";
const content = document.getElementById("output-content");
content.classList.add("visible");
// Store original code for diff
window.originalCode = originalCode;
// Error type + severity
document.getElementById("out-error-type").textContent =
r.error_type || "Unknown Error";
const sevEl = document.getElementById("out-severity");
sevEl.textContent = r.severity ? capitalize(r.severity) : "Unknown";
sevEl.className = "severity-badge sev-" + (r.severity || "beginner");
// Explanation
document.getElementById("out-explanation").textContent =
r.plain_explanation || "—";
// Analogy
document.getElementById("out-analogy").innerHTML = r.desi_analogy
? `<strong>🫖 Desi Analogy:</strong> ${r.desi_analogy}`
: "—";
// Fixed code with syntax highlighting
const langClass =
{
python: "language-python",
javascript: "language-javascript",
java: "language-java",
cpp: "language-cpp",
html: "language-html",
sql: "language-sql",
}[currentLang] || "language-python";
const codeEl = document.getElementById("out-fixed-code");
codeEl.className = langClass;
codeEl.textContent = r.fixed_code || "# No fix generated";
document.getElementById("out-fix-lang").textContent =
LANG_TAGS[currentLang] || "fixed_code.py";
Prism.highlightElement(codeEl);
// Reset diff view
document.getElementById("code-diff-view").style.display = "none";
document.getElementById("out-fixed-code").parentElement.style.display =
"block";
document.getElementById("diff-toggle-btn").textContent = "Show Diff";
// Fix bullets
const fixList = document.getElementById("out-fix-list");
fixList.innerHTML = "";
if (r.fix_bullets && Array.isArray(r.fix_bullets)) {
r.fix_bullets.forEach((bullet) => {
const li = document.createElement("li");
li.textContent = bullet;
fixList.appendChild(li);
});
}
// Concept card
document.getElementById("out-concept-name").textContent =
r.concept_to_study || "General Debugging";
document.getElementById("out-concept-why").textContent = r.concept_why || "";
const conceptLink = document.getElementById("out-concept-link");
const searchQuery =
r.concept_search || r.concept_to_study || "programming debugging tutorial";
conceptLink.href = `https://www.youtube.com/results?search_query=${encodeURIComponent(searchQuery)}`;
conceptLink.textContent = `"${searchQuery}" ↗`;
// Populate share card
document.getElementById("sc-error-type").textContent =
r.error_type || "Error";
const scSev = document.getElementById("sc-severity");
scSev.textContent = capitalize(r.severity || "beginner");
scSev.className = "severity-badge sev-" + (r.severity || "beginner");
document.getElementById("sc-explanation").textContent =
r.plain_explanation || "";
document.getElementById("sc-analogy").textContent = r.desi_analogy || "";
// Check repeat errors
const errorKey = `${currentLang}_${r.mistake_category}`;
const repeatCount = parseInt(
localStorage.getItem("cd_error_repeat_" + errorKey) || "0",
);
const newRepeat = repeatCount + 1;
localStorage.setItem("cd_error_repeat_" + errorKey, newRepeat);
const repeatBanner = document.getElementById("repeat-banner");
if (newRepeat >= 2) {
repeatBanner.style.display = "flex";
const txt = document.getElementById("repeat-banner-text");
if (newRepeat === 2)
txt.textContent =
"You have seen this error type before — good news: now you will recognise it faster.";
else if (newRepeat === 3)
txt.textContent =
"This is the 3rd time — let us go deeper. Focus on the Aab Yeh Seekho concept below.";
else
txt.textContent = `You have hit this error ${newRepeat} times. Time to master this concept once and for all.`;
} else {
repeatBanner.style.display = "none";
}
// Reset understood buttons
document.getElementById("understood-yes").classList.remove("active");
document.getElementById("understood-no").classList.remove("active");
document.getElementById("understood-stats").style.display = "none";
// Scroll output into view on mobile
if (window.innerWidth < 900) {
document
.getElementById("panel-right")
.scrollIntoView({ behavior: "smooth", block: "start" });
}
}
// ═══════════════════════════════════════
// HISTORY
// ═══════════════════════════════════════
function saveToHistory(result, code, errorMsg) {
const entry = {
id: Date.now(),
time: new Date().toLocaleTimeString("en-PK", {
hour: "2-digit",
minute: "2-digit",
}),
errorType: result.error_type,
errorMsg: errorMsg || result.error_type,
lang: currentLang,
code: code,
result: result,
};
sessionHistory.unshift(entry);
if (sessionHistory.length > 20) sessionHistory.pop();
localStorage.setItem("cd_history", JSON.stringify(sessionHistory));
renderHistory();
}
function renderHistory() {
renderHistoryWithNav();
return; // use new nav version
}
function _renderHistoryOld() {
const list = document.getElementById("history-list");
const empty = document.getElementById("history-empty");
const clearBtn = document.getElementById("clear-history-btn");
if (clearBtn) {
clearBtn.onclick = () => {
if (confirm("History clear karna hai?")) {
sessionHistory = [];
localStorage.removeItem("cd_history");
renderHistory();
renderPatterns();
showToast("success", "History cleared");
}
};
}
if (sessionHistory.length === 0) {
empty.classList.remove("hidden");
list.classList.add("hidden");
return;
}
empty.classList.add("hidden");
list.classList.remove("hidden");
list.innerHTML = "";
sessionHistory.forEach((entry) => {
const div = document.createElement("div");
div.className = "history-item";
div.onclick = () => reloadHistory(entry);
div.innerHTML = `
<span class="history-time">${entry.time}</span>
<span class="history-err">${entry.errorMsg || entry.errorType}</span>
<span class="history-lang">${entry.lang}</span>
`;
list.appendChild(div);
});
}