Spaces:
Sleeping

File size: 38,217 Bytes
995c7c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
866b6a2
995c7c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5bfcde2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb9cf48
5bfcde2
 
 
 
 
 
 
 
 
 
 
 
 
995c7c5
 
 
 
866b6a2
 
995c7c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb9cf48
 
5bfcde2
 
 
cb9cf48
 
5bfcde2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb9cf48
5bfcde2
 
 
 
 
 
 
 
 
 
 
cb9cf48
5bfcde2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb9cf48
5bfcde2
 
 
 
 
 
cb9cf48
 
5bfcde2
 
 
 
 
 
 
 
 
 
 
cb9cf48
5bfcde2
 
 
cb9cf48
5bfcde2
 
 
 
995c7c5
 
 
 
 
 
 
cb9cf48
 
 
 
5bfcde2
cb9cf48
 
5bfcde2
 
 
 
 
 
 
 
 
 
 
 
 
cb9cf48
5bfcde2
 
995c7c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
import express from "express";
import path from "path";
import fs from "fs";
import vm from "vm";
import { createServer as createViteServer } from "vite";

const app = express();
const PORT = process.env.PORT ? parseInt(process.env.PORT) : 3000;
const DATA_DIR = path.join(process.cwd(), "data");
const CONFIG_PATH = path.join(DATA_DIR, "config.json");

// Ensure data directory exists
if (!fs.existsSync(DATA_DIR)) {
  fs.mkdirSync(DATA_DIR, { recursive: true });
}

// Interfaces
interface Channel {
  id: string;
  name: string;
  url: string;
  logo: string;
  overrideUrl: string;
  m3u8Url: string | null;
  referer: string | null;
  status: "Active" | "No Stream" | "Override" | "Error" | "Pending";
  lastTested: string | null;
  logs: string[];
}

interface AppConfig {
  userAgent: string;
  referer: string;
  scrapeIntervalMs: number;
  channels: Channel[];
  enableHfPush?: boolean;
  hfToken?: string;
  hfSpace?: string;
}

const DEFAULT_CHANNELS: Channel[] = [];

const DEFAULT_CONFIG: AppConfig = {
  userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
  referer: "https://11.yallashoot1.cc/",
  scrapeIntervalMs: 3600000, // 1 hour
  channels: DEFAULT_CHANNELS,
  enableHfPush: true,
  hfToken: process.env.HF_TOKEN || "",
  hfSpace: "subrato1/streamapi"
};

// State
let appConfig: AppConfig = { ...DEFAULT_CONFIG };
let lastUpdated: string | null = null;
let isScraping = false;
let globalLogs: string[] = [];

// Load config
function loadConfig() {
  try {
    if (fs.existsSync(CONFIG_PATH)) {
      const data = JSON.parse(fs.readFileSync(CONFIG_PATH, "utf-8"));
      // Merge properties safely
      appConfig = {
        userAgent: data.userAgent || DEFAULT_CONFIG.userAgent,
        referer: data.referer || DEFAULT_CONFIG.referer,
        scrapeIntervalMs: data.scrapeIntervalMs || DEFAULT_CONFIG.scrapeIntervalMs,
        enableHfPush: data.enableHfPush !== undefined ? data.enableHfPush : DEFAULT_CONFIG.enableHfPush,
        hfToken: data.hfToken !== undefined ? data.hfToken : DEFAULT_CONFIG.hfToken,
        hfSpace: data.hfSpace !== undefined ? data.hfSpace : DEFAULT_CONFIG.hfSpace,
        channels: [
          ...DEFAULT_CONFIG.channels.map(defaultCh => {
            const savedCh = (data.channels || []).find((c: any) => c.id === defaultCh.id);
            return {
              ...defaultCh,
              name: savedCh?.name || defaultCh.name,
              url: savedCh?.url || defaultCh.url,
              logo: savedCh?.logo || defaultCh.logo,
              overrideUrl: savedCh?.overrideUrl || defaultCh.overrideUrl,
              m3u8Url: savedCh?.m3u8Url || defaultCh.m3u8Url,
              referer: savedCh?.referer || defaultCh.referer || null,
              status: savedCh?.status || defaultCh.status,
              lastTested: savedCh?.lastTested || defaultCh.lastTested,
              logs: savedCh?.logs || defaultCh.logs
            };
          }),
          ...(data.channels || [])
            .filter((savedCh: any) => savedCh.id && (savedCh.id.startsWith("fifa-") || savedCh.id.startsWith("rugby-")))
            .map((savedCh: any) => ({
              id: savedCh.id,
              name: savedCh.name,
              url: savedCh.url,
              logo: savedCh.logo || "https://cdn-icons-png.flaticon.com/512/3076/3076841.png",
              overrideUrl: savedCh.overrideUrl || "",
              m3u8Url: savedCh.m3u8Url || null,
              referer: savedCh.referer || null,
              status: savedCh.status || "Pending",
              lastTested: savedCh.lastTested || null,
              logs: savedCh.logs || []
            }))
        ]
      };
      if (data.lastUpdated) {
        lastUpdated = data.lastUpdated;
      }
      console.log("Config loaded and cleaned successfully.");
      saveConfig();
    } else {
      saveConfig();
    }
  } catch (error) {
    console.error("Error loading config:", error);
  }
}

// Save config
function saveConfig() {
  try {
    fs.writeFileSync(CONFIG_PATH, JSON.stringify({ ...appConfig, lastUpdated }, null, 2), "utf-8");
  } catch (error) {
    console.error("Error saving config:", error);
  }
}

loadConfig();

// Custom fetch helper with maximum execution timeout to prevent crawler hangs
async function fetchWithTimeout(url: string, options: any = {}, timeoutMs = 8000) {
  const controller = new AbortController();
  const id = setTimeout(() => controller.abort(), timeoutMs);
  try {
    const response = await fetch(url, {
      ...options,
      signal: controller.signal
    });
    return response;
  } finally {
    clearTimeout(id);
  }
}

// Custom fetch helper that wraps both fetch and body reading to prevent stalls during body reading
async function fetchTextWithTimeout(url: string, options: any = {}, timeoutMs = 8000): Promise<string> {
  const controller = new AbortController();
  const id = setTimeout(() => {
    controller.abort();
  }, timeoutMs);
  try {
    const response = await fetch(url, {
      ...options,
      signal: controller.signal
    });
    if (!response.ok) {
      throw new Error(`HTTP ${response.status} ${response.statusText}`);
    }
    const text = await response.text();
    return text;
  } finally {
    clearTimeout(id);
  }
}

// Special scraper for playerAio protected embeds
async function scrapePlayerAio(targetUrl: string, userAgent: string, defaultReferer: string): Promise<{ m3u8Url: string | null; referer: string | null; logs: string[] }> {
  const logs: string[] = [];
  logs.push(`[${new Date().toISOString()}] Initiating PlayerAio premium scraper for: ${targetUrl}`);
  try {
    let html: string;
    try {
      html = await fetchTextWithTimeout(targetUrl, {
        headers: {
          "User-Agent": userAgent,
          "Referer": defaultReferer || "https://playeraio.top/",
          "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"
        },
        method: "GET"
      }, 8000);
    } catch (fetchErr: any) {
      logs.push(`Failed to fetch playeraio page: ${fetchErr.message}`);
      return { m3u8Url: null, referer: null, logs };
    }

    const vconMatch = html.match(/v_con\s*=\s*["']([^"']+)["']/i);
    const vdtMatch = html.match(/v_dt\s*=\s*["']([^"']+)["']/i);
    const fidMatch = html.match(/fid\s*=\s*["']([^"']+)["']/i);

    const v_con = vconMatch ? vconMatch[1] : null;
    const v_dt = vdtMatch ? vdtMatch[1] : null;
    const fid = fidMatch ? fidMatch[1] : null;

    if (!v_con || !v_dt || !fid) {
      logs.push(`Failed to extract player variables: v_con=${v_con}, v_dt=${v_dt}, fid=${fid}`);
      return { m3u8Url: null, referer: null, logs };
    }

    logs.push(`Extracted player variables: fid=${fid}, secure=${v_con}, expires=${v_dt}`);
    
    const bhalocastUrl = `https://bhalocast.pro/atofplay.php?v=${fid}&secure=${v_con}&expires=${v_dt}`;
    logs.push(`Fetching decrypted iframe page: ${bhalocastUrl}`);

    let bhaloHtml: string;
    try {
      bhaloHtml = await fetchTextWithTimeout(bhalocastUrl, {
        headers: {
          "User-Agent": userAgent,
          "Referer": targetUrl
        }
      }, 8000);
    } catch (fetchErr: any) {
      logs.push(`Failed to fetch bhalocast page: ${fetchErr.message}`);
      return { m3u8Url: null, referer: null, logs };
    }
    const arrayRegex = /\["h"\s*,\s*"t"\s*,\s*"t"\s*,\s*"p"\s*,\s*"s"[^\]]+\]/g;
    const matches = bhaloHtml.match(arrayRegex);
    if (!matches || matches.length === 0) {
      logs.push(`Could not find any stream array source matches in the bhalocast HTML structure.`);
      return { m3u8Url: null, referer: null, logs };
    }

    logs.push(`Found ${matches.length} stream source array matches.`);
    
    let resolvedUrl: string | null = null;
    for (let i = matches.length - 1; i >= 0; i--) {
      try {
        const parsed = JSON.parse(matches[i]);
        const urlStr = parsed.join("");
        if (urlStr.startsWith("http") && urlStr.includes(".m3u8")) {
          logs.push(`Testing stream source match ${i}: ${urlStr}`);
          const testRes = await fetchWithTimeout(urlStr, {
            headers: {
              "User-Agent": userAgent,
              "Referer": "https://bhalocast.pro/",
              "Origin": "https://bhalocast.pro"
            }
          }, 3000);
          logs.push(`Stream test status for match ${i}: ${testRes.status}`);
          if (testRes.status === 200 || testRes.status === 206) {
            resolvedUrl = urlStr;
            break;
          }
        }
      } catch (err: any) {
        logs.push(`JSON parsing error for match ${i}: ${err.message}`);
      }
    }

    if (!resolvedUrl && matches.length > 0) {
      try {
        const idx = matches.length > 1 ? 1 : 0;
        resolvedUrl = JSON.parse(matches[idx]).join("");
        logs.push(`Fallback to match ${idx}: ${resolvedUrl}`);
      } catch (err) {
        // Ignore
      }
    }

    if (resolvedUrl) {
      return { m3u8Url: resolvedUrl, referer: "https://bhalocast.pro/", logs };
    }

    return { m3u8Url: null, referer: null, logs };
  } catch (error: any) {
    logs.push(`PlayerAio scraping error: ${error?.message || error}`);
    return { m3u8Url: null, referer: null, logs };
  }
}

// Scraper function
async function scrapeUrl(targetUrl: string, userAgent: string, referer: string, depth = 0): Promise<{ m3u8Url: string | null; referer: string | null; logs: string[] }> {
  if (targetUrl && (targetUrl.includes("playeraio.top") || targetUrl.includes("embed2.php"))) {
    return scrapePlayerAio(targetUrl, userAgent, referer);
  }
  const logs: string[] = [];
  logs.push(`[${new Date().toISOString()}] Initiating fetch for target: ${targetUrl}`);
  try {
    let html: string;
    try {
      html = await fetchTextWithTimeout(targetUrl, {
        headers: {
          "User-Agent": userAgent,
          "Referer": referer,
          "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
          "Accept-Language": "en-US,en;q=0.5",
          "Cache-Control": "max-age=0"
        },
        method: "GET"
      }, 8000);
    } catch (fetchErr: any) {
      logs.push(`Failed to fetch page: ${fetchErr.message}`);
      return { m3u8Url: null, referer: null, logs };
    }

    logs.push(`Page fetched successfully. HTML content length: ${html.length} characters.`);

    // 1. Direct Regex search for any .m3u8 URLs in the HTML
    const m3u8Regex = /(https?:\/\/[^"'\s<>]+?\.m3u8[^"'\s<>]*)/gi;
    let match;
    const foundUrls: string[] = [];
    while ((match = m3u8Regex.exec(html)) !== null) {
      const u = match[1];
      // Skip common static placeholder/images/js if they somehow match m3u8
      if (!u.includes("favicon") && !u.includes("assets")) {
        foundUrls.push(u);
      }
    }

    if (foundUrls.length > 0) {
      logs.push(`Found ${foundUrls.length} direct .m3u8 stream links.`);
      // Return first clean url found
      return { m3u8Url: foundUrls[0], referer: targetUrl, logs };
    }

    // 2. Base64 encoded streams. Often sport pages obfuscate sources inside base64: atob("aHR0cHM6Ly8...")
    logs.push(`Scanning for Base64 obfuscated URLs...`);
    const base64Regex = /[A-Za-z0-9+/]{40,}/g;
    const bMatches = html.match(base64Regex) || [];
    for (const bStr of bMatches) {
      // "aHR0c" is the base64 code for "http"
      if (bStr.includes("aHR0c")) {
        try {
          const decoded = Buffer.from(bStr, "base64").toString("utf-8");
          if (decoded.startsWith("http") && decoded.includes(".m3u8")) {
            logs.push(`Successfully found & decoded obfuscated stream: "${decoded}"`);
            return { m3u8Url: decoded, referer: targetUrl, logs };
          }
        } catch (_) {}
      }
    }

    // 3. Search common variable declarations (source, file, url, src)
    const propertyPatterns = [
      /source\s*:\s*["']([^"']+\.m3u8[^"']*)["']/i,
      /file\s*:\s*["']([^"']+\.m3u8[^"']*)["']/i,
      /src\s*:\s*["']([^"']+\.m3u8[^"']*)["']/i,
      /url\s*:\s*["']([^"']+\.m3u8[^"']*)["']/i,
      /videoSrc\s*=\s*["']([^"']+\.m3u8[^"']*)["']/i
    ];

    for (const pat of propertyPatterns) {
      const match = html.match(pat);
      if (match && match[1]) {
        logs.push(`Found stream within javascript player variables: ${match[1]}`);
        return { m3u8Url: match[1], referer: targetUrl, logs };
      }
    }

    // 3.5 Check for dynadopt.net player page or if window._econfig is present
    if (html.includes("window._econfig")) {
      logs.push("Detected dynadopt.net player payload: attempting VM decrypter...");
      const match = html.match(/window\._econfig\s*=\s*['"]([^'"]+)['"]/);
      if (match && match[1]) {
        const econfig = match[1];
        logs.push(`Found _econfig string of length ${econfig.length}`);
        try {
          const parsedUrl = new URL(targetUrl);
          const jsUrl = `${parsedUrl.origin}/assets/stream.js?_v=0.0.19`;
          logs.push(`Configuring VM execution context and fetching decoding script: ${jsUrl}`);
          let jsCode: string;
          try {
            jsCode = await fetchTextWithTimeout(jsUrl, {
              headers: {
                "User-Agent": userAgent,
                "Referer": targetUrl
              }
            }, 5000);
          } catch (jsErr: any) {
            throw new Error(`Failed to fetch stream.js: ${jsErr.message}`);
          }
          logs.push(`Downloaded stream.js (${jsCode.length} bytes). Launching secure VM sandbox...`);

          let decryptedM3u8: string | null = null;
          const createMockElement = () => {
            const el: any = {
              style: {},
              classList: {
                add: () => el,
                remove: () => el,
                contains: () => false,
              },
              setAttribute: () => el,
              getAttribute: () => "",
              removeAttribute: () => el,
              appendChild: () => el,
              removeChild: () => el,
              remove: () => el,
              addEventListener: () => {},
              innerHTML: "",
              textContent: "",
              innerText: "",
            };
            return el;
          };

          const createChainableMock = () => {
            const thenable = {
              then: (cb: any) => {
                try { if (typeof cb === "function") cb(); } catch (e) {}
                return thenable;
              },
              catch: (cb: any) => {
                return thenable;
              }
            };
            const fn = () => thenable;
            Object.setPrototypeOf(fn, thenable);
            return fn;
          };

          const mockP2PProxy = new Proxy(() => {}, {
            get: (target, prop) => {
              if (typeof prop === "symbol") return undefined;
              return createChainableMock();
            }
          });

          const mockWindow: any = {
            _econfig: econfig,
            atob: (str: string) => Buffer.from(str, "base64").toString("binary"),
            btoa: (str: string) => Buffer.from(str, "binary").toString("base64"),
            location: {
              href: targetUrl,
              hostname: parsedUrl.hostname,
              protocol: parsedUrl.protocol,
              origin: parsedUrl.origin,
              reload: () => {}
            },
            navigator: {
              userAgent: userAgent
            },
            addEventListener: () => {},
            removeEventListener: () => {},
            clearInterval: () => {},
            setInterval: () => {},
            setTimeout: () => {},
            clearTimeout: () => {},
            P2PEngineHls: mockP2PProxy,
            P2pEngineHls: mockP2PProxy,
            Clappr: {
              Player: class MockClappr {
                constructor(config: any) {
                  if (config && config.source) {
                    decryptedM3u8 = config.source;
                  }
                }
              }
            }
          };

          mockWindow.window = mockWindow;
          mockWindow.top = mockWindow;
          mockWindow.self = mockWindow;

          const mockDocument: any = {
            location: mockWindow.location,
            referrer: referer,
            addEventListener: () => {},
            removeEventListener: () => {},
            createElement: (tag: string) => createMockElement(),
            getElementById: () => createMockElement(),
            getElementsByTagName: () => [{ parentNode: { insertBefore: () => {} } }],
            querySelector: () => createMockElement(),
            querySelectorAll: () => [],
            body: {
              appendChild: () => {},
              innerHTML: ""
            }
          };

          mockWindow.document = mockDocument;

          const context = vm.createContext(mockWindow);
          vm.runInContext(jsCode, context, { timeout: 4000 });

          if (decryptedM3u8) {
            logs.push(`VM decryption successful! Found stream source: "${decryptedM3u8}"`);
            const originReferer = parsedUrl.origin + "/";
            return { m3u8Url: decryptedM3u8, referer: originReferer, logs };
          } else {
            logs.push("VM execution completed but failed to capture m3u8 stream.");
          }
        } catch (vmErr: any) {
          logs.push(`VM Decrypt failed: ${vmErr.message}`);
        }
      } else {
        logs.push("Detected window._econfig pattern but matches are empty.");
      }
    }

    // 4. Look for embedded iframes (e.g., albaplayer uses standard players or streams inside iframes)
    logs.push(`Looking for nested frames...`);
    const iframeRegex = /<iframe[^>]+src=["']([^"']+)["']/i;
    const iframeMatch = html.match(iframeRegex);
    if (iframeMatch && iframeMatch[1]) {
      const iframeUrl = iframeMatch[1];
      logs.push(`Detected iframe source: ${iframeUrl}`);

      let targetIframe = iframeUrl;
      if (iframeUrl.startsWith("//")) {
        targetIframe = "https:" + iframeUrl;
      } else if (iframeUrl.startsWith("/")) {
        const parsedTargetUrl = new URL(targetUrl);
        targetIframe = `${parsedTargetUrl.origin}${iframeUrl}`;
      }

      if (depth >= 2) {
        logs.push(`Interrupting iframe traversal: Max depth limit of 2 reached. Preempting loop on: ${targetIframe}`);
      } else {
        logs.push(`Entering nested iframe scraper: ${targetIframe} (Depth: ${depth + 1})`);
        let nestedReferer = targetUrl;
        try {
          const parsedParent = new URL(targetUrl);
          nestedReferer = parsedParent.origin + "/";
        } catch (_) {}

        const nestedScrape = await scrapeUrl(targetIframe, userAgent, nestedReferer, depth + 1);
        logs.push(...nestedScrape.logs.map(l => "  [Nested Frame] " + l));
        if (nestedScrape.m3u8Url) {
          return { m3u8Url: nestedScrape.m3u8Url, referer: nestedScrape.referer || targetIframe, logs };
        }
      }
    }

    logs.push("Could not extract any active .m3u8 link from the page structure directly.");
    logs.push(`Failed Page Snippet: ${html.substring(0, 1500).replace(/\s+/g, ' ')}`);
    return { m3u8Url: null, referer: null, logs };
  } catch (error: any) {
    logs.push(`Network or extraction failure: ${error?.message || error}`);
    return { m3u8Url: null, referer: null, logs };
  }
}

// Discover FIFA World Cup streams from footystream.pk
async function discoverFifaStreams(): Promise<Channel[]> {
  const discovered: Channel[] = [];
  const ua = appConfig.userAgent;
  try {
    globalLogs.push(`[${new Date().toISOString()}] FIFA Discovery: Initiating fetch for https://footystream.pk/leagues/fifa-world-cup`);
    const mainHtml = await fetchTextWithTimeout("https://footystream.pk/leagues/fifa-world-cup", {
      headers: { "User-Agent": ua }
    });
    
    const eventRegex = /href=["']([^"']+\/events\/[^"']+)["']/gi;
    let match;
    const events = new Set<string>();
    while ((match = eventRegex.exec(mainHtml)) !== null) {
      events.add(match[1]);
    }
    const relativeEventRegex = /href=["'](\/events\/[^"']+)["']/gi;
    while ((match = relativeEventRegex.exec(mainHtml)) !== null) {
      events.add("https://footystream.pk" + match[1]);
    }

    const eventList = Array.from(events);
    globalLogs.push(`[${new Date().toISOString()}] FIFA Discovery: Found ${eventList.length} FIFA World Cup event pages.`);

    for (const eventUrl of eventList) {
      try {
        const eventSlugMatch = eventUrl.match(/\/events\/([^/?#]+)/);
        if (!eventSlugMatch) continue;
        const eventSlug = eventSlugMatch[1];
        const eventTitle = eventSlug
          .split("-")
          .map(word => word.charAt(0).toUpperCase() + word.slice(1))
          .join(" ");

        globalLogs.push(`[${new Date().toISOString()}] FIFA Discovery: Processing event: ${eventTitle}`);
        const eventHtml = await fetchTextWithTimeout(eventUrl, {
          headers: { "User-Agent": ua }
        });

        const alphaRegex = /href=["']([^"']+\/alpha\/[^"']+)["']/gi;
        const alphaServers = new Set<string>();
        while ((match = alphaRegex.exec(eventHtml)) !== null) {
          alphaServers.add(match[1]);
        }
        const relativeAlphaRegex = /href=["'](\/alpha\/[^"']+)["']/gi;
        while ((match = relativeAlphaRegex.exec(eventHtml)) !== null) {
          alphaServers.add("https://footystream.pk" + match[1]);
        }

        const serverList = Array.from(alphaServers);
        globalLogs.push(`[${new Date().toISOString()}] FIFA Discovery: Found ${serverList.length} alpha server(s) for event.`);

        for (const serverUrl of serverList) {
          const serverIdMatch = serverUrl.match(/\/alpha\/[^/]+\/(\d+)/i);
          const serverId = serverIdMatch ? serverIdMatch[1] : "1";
          
          discovered.push({
            id: `fifa-${eventSlug}-${serverId}`,
            name: `FIFA: ${eventTitle} - Server ${serverId}`,
            url: serverUrl,
            logo: "https://cdn-icons-png.flaticon.com/512/3076/3076841.png",
            overrideUrl: "",
            m3u8Url: null,
            referer: null,
            status: "Pending",
            lastTested: null,
            logs: []
          });
        }
      } catch (err: any) {
        globalLogs.push(`[${new Date().toISOString()}] FIFA Discovery: Failed to process event ${eventUrl}: ${err.message}`);
      }
    }
  } catch (err: any) {
    globalLogs.push(`[${new Date().toISOString()}] FIFA Discovery: Failed: ${err.message}`);
  }
  return discovered;
}

// Full Run
async function runCompleteScraper() {
  if (isScraping) return;
  isScraping = true;
  globalLogs = [`[${new Date().toISOString()}] Started live streaming extractor cycle.`];

  try {
    // Dynamically discover FIFA streams and update configuration channels
    const discoveredFifa = await discoverFifaStreams();
    const staticChannels = appConfig.channels.filter(ch => !ch.id.startsWith("fifa-") && !ch.id.startsWith("rugby-"));
    const existingFifa = appConfig.channels.filter(ch => ch.id.startsWith("fifa-"));

    const mergedFifa = discoveredFifa.map(newCh => {
      const match = existingFifa.find(oldCh => oldCh.id === newCh.id);
      if (match) {
        return {
          ...newCh,
          status: match.status,
          m3u8Url: match.m3u8Url,
          referer: match.referer,
          lastTested: match.lastTested,
          logs: match.logs
        };
      }
      return newCh;
    });

    appConfig.channels = [...staticChannels, ...mergedFifa];
    saveConfig();

    const total = appConfig.channels.length;
    for (let idx = 0; idx < total; idx++) {
      const ch = appConfig.channels[idx];
      if (ch.overrideUrl) {
        ch.status = "Override";
        ch.m3u8Url = ch.overrideUrl;
        ch.lastTested = new Date().toISOString();
        ch.logs = [`Channel has active custom stream URL overrides, skipping crawl: ${ch.overrideUrl}`];
        saveConfig();
        continue;
      }

      ch.status = "Pending";
      globalLogs.push(`[${new Date().toISOString()}] (${idx + 1}/${total}) Crawling: ${ch.name}...`);
      saveConfig();

      const start = Date.now();
      const result = await scrapeUrl(ch.url, appConfig.userAgent, appConfig.referer);
      
      ch.logs = result.logs;
      ch.lastTested = new Date().toISOString();

      if (result.m3u8Url) {
        ch.m3u8Url = result.m3u8Url;
        ch.referer = result.referer;
        ch.status = "Active";
        ch.logs.push(`Scrape successful in ${Date.now() - start}ms. Saved source.`);
        globalLogs.push(`[${new Date().toISOString()}] (${idx + 1}/${total}) Success: ${ch.name}`);
      } else {
        ch.m3u8Url = null;
        ch.referer = null;
        ch.status = "No Stream";
        ch.logs.push(`Failing link discovery. Stream marked offline.`);
        globalLogs.push(`[${new Date().toISOString()}] (${idx + 1}/${total}) Failed: ${ch.name}`);
      }
      saveConfig();
    }

    lastUpdated = new Date().toISOString();
    saveConfig();
    
    // Auto sync with Hugging Face Space
    await pushToHuggingFace();
  } catch (e: any) {
    globalLogs.push(`Fatal error in extractor cycle: ${e?.message || e}`);
  } finally {
    isScraping = false;
  }
}

// Direct M3U Playlist Content Generator
function generateM3uContent(type: "standard" | "suffix" | "ott" | "raw"): string {
  let m3u = "#EXTM3U\n";

  appConfig.channels.forEach((ch) => {
    const finalStreamUrl = ch.m3u8Url;
    if (!finalStreamUrl) return;

    // Logo default fallback
    const logoUrl = ch.logo || "https://cdn-icons-png.flaticon.com/512/861/861512.png";
    const displayName = ch.name;

    m3u += `#EXTINF:-1 tvg-logo="${logoUrl}",${displayName}\n`;

    let refererToUse = ch.referer || appConfig.referer;
    let origin = "";
    try {
      if (refererToUse) {
        origin = new URL(refererToUse).origin;
      }
    } catch (_) {
      origin = refererToUse;
    }

    if (type === "standard") {
      // VLC format: separate properties
      m3u += `#EXTVLCOPT:http-referrer=${refererToUse}\n`;
      if (origin) {
        m3u += `#EXTVLCOPT:http-origin=${origin}\n`;
      }
      m3u += `${finalStreamUrl}\n`;
    } else if (type === "suffix") {
      // Suffix header parameters format (useful for TiviMate, OTT Navigator etc.)
      const connectionParams = `|User-Agent=${encodeURIComponent(appConfig.userAgent)}&Referer=${encodeURIComponent(refererToUse)}`;
      m3u += `${finalStreamUrl}${connectionParams}\n`;
    } else if (type === "ott") {
      // Alternative tag directives format
      m3u += `#EXTHTTP:{"User-Agent":"${appConfig.userAgent}","Referer":"${refererToUse}"}\n`;
      m3u += `${finalStreamUrl}\n`;
    } else {
      // Plain
      m3u += `${finalStreamUrl}\n`;
    }
  });

  return m3u;
}

// Push Generated Playlist to Hugging Face Space
async function pushToHuggingFace() {
  if (!appConfig.enableHfPush) {
    globalLogs.push(`[HuggingFace API] Push is disabled in settings.`);
    return;
  }

  const token = appConfig.hfToken || process.env.HF_TOKEN || "";
  const space = appConfig.hfSpace || "subrato1/streamapi";

  if (!token || !space) {
    globalLogs.push(`[HuggingFace API] Push missing required token or Space path.`);
    return;
  }

  globalLogs.push(`[HuggingFace API] Initiating git push to HF Space: ${space}`);
  const tempDir = path.join(process.cwd(), "data", `hf_push_${Date.now()}`);

  try {
    const { execSync } = await import("child_process");
    // 1. Generate M3U playlist content
    const m3uContent = generateM3uContent("standard");

    // 2. Clone space repository
    globalLogs.push(`[HuggingFace API] Cloning repo target info...`);
    const hfGitUrl = `https://user:${token}@huggingface.co/spaces/${space}`;
    
    // Silence git clone prompts to avoid hanging if auth fails
    execSync(`git clone ${hfGitUrl} ${tempDir} --depth 1`, { 
      env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
      stdio: "ignore",
      timeout: 30000 // 30 seconds execution timeout
    });

    if (!fs.existsSync(tempDir)) {
      throw new Error("Target folder not created after cloning command.");
    }

    // 3. Write playlist file inside clone
    const destinationPath = path.join(tempDir, "yallashoot_playlist.m3u");
    fs.writeFileSync(destinationPath, m3uContent, "utf-8");

    // 4. Git configure, add, commit & push
    const gitCmd = (cmd: string) => {
      return execSync(cmd, { 
        cwd: tempDir, 
        encoding: "utf8", 
        env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
        timeout: 20000 // 20 seconds execution timeout
      });
    };

    gitCmd(`git config user.name "M3u8 Stream Auto Updater"`);
    gitCmd(`git config user.email "auto-updater@streamapi.com"`);
    gitCmd(`git add yallashoot_playlist.m3u`);

    const statusMap = gitCmd(`git status --porcelain`).trim();
    if (statusMap.length === 0) {
      globalLogs.push(`[HuggingFace API] Playlist is already up to date on Space. No push needed.`);
    } else {
      globalLogs.push(`[HuggingFace API] Committing playlist changes...`);
      gitCmd(`git commit -m "Auto-update playlist: ${new Date().toISOString()}"`);
      
      globalLogs.push(`[HuggingFace API] Pushing commits securely...`);
      gitCmd(`git push origin main`);
      globalLogs.push(`[HuggingFace API] Push successfully completed and synced to Hugging Face Space!`);
    }

  } catch (error: any) {
    globalLogs.push(`[HuggingFace API] Error pushing to Space: ${error?.message || error}`);
    console.error("Huggingface push err:", error);
  } finally {
    // 5. Clean up temporary directory
    if (fs.existsSync(tempDir)) {
      try {
        fs.rmSync(tempDir, { recursive: true, force: true });
      } catch (err: any) {
        console.error("Cleanup temp dir error:", err);
      }
    }
  }
}

// Initial background scrape on server start
setTimeout(() => {
  console.log("Triggering initialization scrape...");
  runCompleteScraper();
}, 2000);

// Setup hourly interval for automatic scraping
let schedulerInterval = setInterval(() => {
  console.log("Triggering periodic hourly auto-updater...");
  runCompleteScraper();
}, appConfig.scrapeIntervalMs);

// Helper to rebuild dynamic scheduler if interval is updated
function restartInterval() {
  clearInterval(schedulerInterval);
  schedulerInterval = setInterval(() => {
    console.log(`Triggering periodic auto-updater every ${appConfig.scrapeIntervalMs / 60000} minutes`);
    runCompleteScraper();
  }, appConfig.scrapeIntervalMs);
}

// API Routes
app.use(express.json());

// Secure Stream Proxy to bypass browser CORS / Referer restrictions
app.get("/api/stream-proxy", async (req, res) => {
  const target = req.query.url as string;
  const queryReferer = req.query.referer as string;
  if (!target) {
    return res.status(400).send("Missing url parameter");
  }

  try {
    let refererToUse = queryReferer || appConfig.referer || "https://11.yallashoot1.cc/";
    if (!queryReferer) {
      if (target.includes("09193519.net") || target.includes("12703830.net") || target.includes("dynadopt.net")) {
        // Find matching channel to retrieve the dynamic discovered referer
        const matchingChannel = appConfig.channels.find(ch => {
          if (!ch.m3u8Url) return false;
          try {
            const chPath = new URL(ch.m3u8Url).pathname;
            const targetPath = new URL(target).pathname;
            return chPath === targetPath || target.includes(ch.m3u8Url) || ch.m3u8Url.includes(target.split('?')[0]);
          } catch (_) {
            return target.includes(ch.m3u8Url) || ch.m3u8Url.includes(target.split('?')[0]);
          }
        });
        if (matchingChannel && matchingChannel.referer) {
          refererToUse = matchingChannel.referer;
        } else {
          // Heuristic fallback if not specified: find any active channel that holds a dynadopt.net referer
          const anyDynChannel = appConfig.channels.find(ch => ch.referer && ch.referer.includes("dynadopt.net"));
          refererToUse = anyDynChannel?.referer || "https://d21201b285d0052ce3c7e2cd2e62d5d5.dynadopt.net/";
        }
      }
    }

    const headers: any = {
      "User-Agent": appConfig.userAgent,
      "Referer": refererToUse,
      "Accept": "*/*"
    };

    const response = await fetchWithTimeout(target, { headers }, 15000);

    // Inject permissive CORS headers for browser player sandbox
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Headers", "*");
    res.setHeader("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS");

    // Copy Content-Type cleanly
    const contentType = response.headers.get("content-type");
    if (contentType) {
      res.setHeader("Content-Type", contentType);
    }

    const targetUrlObj = new URL(target);
    const isPlaylist = targetUrlObj.pathname.endsWith(".m3u8") || 
                       contentType?.includes("application/vnd.apple.mpegurl") || 
                       contentType?.includes("mpegurl");

    if (isPlaylist) {
      let text = await response.text();
      const lines = text.split("\n");
      const rewrittenLines = lines.map(line => {
        const trimmed = line.trim();
        if (!trimmed || trimmed.startsWith("#")) {
          return line;
        }

        let absoluteUrl = trimmed;
        if (!trimmed.startsWith("http")) {
          try {
            absoluteUrl = new URL(trimmed, targetUrlObj.href).href;
          } catch (_) {
            return line;
          }
        }

        const host = req.get("host") || "localhost:3000";
        let proxyUrl = `${req.protocol}://${host}/api/stream-proxy?url=${encodeURIComponent(absoluteUrl)}`;
        if (refererToUse) {
          proxyUrl += `&referer=${encodeURIComponent(refererToUse)}`;
        }
        return proxyUrl;
      });
      return res.send(rewrittenLines.join("\n"));
    } else {
      // Stream buffer chunk
      const buffer = await response.arrayBuffer();
      return res.send(Buffer.from(buffer));
    }
  } catch (err: any) {
    console.error(`Stream proxy failure: ${err.message}`);
    res.status(500).send(`Proxy Error: ${err.message}`);
  }
});

// Get status
app.get("/api/status", (req, res) => {
  res.json({
    lastUpdated,
    isScraping,
    globalLogs,
    config: {
      userAgent: appConfig.userAgent,
      referer: appConfig.referer,
      scrapeIntervalMs: appConfig.scrapeIntervalMs,
      enableHfPush: appConfig.enableHfPush || false,
      hfToken: appConfig.hfToken || "",
      hfSpace: appConfig.hfSpace || ""
    },
    channels: appConfig.channels
  });
});

// Run Manual Extract
app.post("/api/extract", async (req, res) => {
  if (isScraping) {
    return res.status(409).json({ error: "Extractor is already in progress, please wait." });
  }
  await runCompleteScraper();
  res.json({
    success: true,
    channels: appConfig.channels,
    lastUpdated
  });
});

// Update single channel custom configuration
app.post("/api/update-channel", (req, res) => {
  const { id, name, url, logo, overrideUrl } = req.body;
  const index = appConfig.channels.findIndex(c => c.id === id);
  if (index === -1) {
    return res.status(404).json({ error: "Channel not found" });
  }

  appConfig.channels[index] = {
    ...appConfig.channels[index],
    name: name !== undefined ? name : appConfig.channels[index].name,
    url: url !== undefined ? url : appConfig.channels[index].url,
    logo: logo !== undefined ? logo : appConfig.channels[index].logo,
    overrideUrl: overrideUrl !== undefined ? overrideUrl : appConfig.channels[index].overrideUrl,
  };

  // Re-adjust status if override is changed
  if (overrideUrl) {
    appConfig.channels[index].m3u8Url = overrideUrl;
    appConfig.channels[index].status = "Override";
    appConfig.channels[index].lastTested = new Date().toISOString();
  } else if (appConfig.channels[index].status === "Override") {
    appConfig.channels[index].status = "Pending";
    appConfig.channels[index].m3u8Url = null;
  }

  saveConfig();
  res.json({ success: true, channel: appConfig.channels[index] });
});

// Update global config
app.post("/api/update-config", (req, res) => {
  const { userAgent, referer, scrapeIntervalMs, enableHfPush, hfToken, hfSpace } = req.body;

  if (userAgent !== undefined) appConfig.userAgent = userAgent;
  if (referer !== undefined) appConfig.referer = referer;
  if (scrapeIntervalMs !== undefined && typeof scrapeIntervalMs === "number" && scrapeIntervalMs >= 60000) {
    appConfig.scrapeIntervalMs = scrapeIntervalMs;
    restartInterval();
  }
  if (enableHfPush !== undefined) appConfig.enableHfPush = enableHfPush;
  if (hfToken !== undefined) appConfig.hfToken = hfToken;
  if (hfSpace !== undefined) appConfig.hfSpace = hfSpace;

  saveConfig();
  res.json({
    success: true,
    config: {
      userAgent: appConfig.userAgent,
      referer: appConfig.referer,
      scrapeIntervalMs: appConfig.scrapeIntervalMs,
      enableHfPush: appConfig.enableHfPush,
      hfToken: appConfig.hfToken,
      hfSpace: appConfig.hfSpace
    }
  });
});

// Direct text representation generator of m3u playlist
app.get("/playlist.m3u", (req, res) => {
  const { format } = req.query; // standard | suffix | raw | ott
  const type = format || "standard";

  let m3u = generateM3uContent(type as any);

  res.setHeader("Content-Type", "application/x-mpegurl; charset=utf-8");
  res.setHeader("Content-Disposition", `attachment; filename="yallashoot_playlist.m3u"`);
  res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
  res.send(m3u);
});

// Setup Vite & Frontend static routing
async function init() {
  if (process.env.NODE_ENV !== "production") {
    const vite = await createViteServer({
      server: { middlewareMode: true },
      appType: "spa",
    });
    app.use(vite.middlewares);
  } else {
    const distPath = path.join(process.cwd(), "dist");
    app.use(express.static(distPath));
    app.get("*", (req, res) => {
      res.sendFile(path.join(distPath, "index.html"));
    });
  }

  app.listen(PORT, "0.0.0.0", () => {
    console.log(`Server started successfully on http://localhost:${PORT}`);
  });
}

init();