-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1433 lines (1306 loc) · 66.2 KB
/
Copy pathindex.html
File metadata and controls
1433 lines (1306 loc) · 66.2 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DataForge</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<style>
:root {
--bg: #ffffff;
--border: #d0d0d0;
--text: #333333;
--text-dim: #666666;
--text-muted: #999999;
--accent: #2563eb;
--success: #16a34a;
--error: #dc2626;
}
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
background: var(--bg);
color: var(--text);
font-size: 14px;
line-height: 1.5;
}
.app { max-width: 560px; margin: 0 auto; padding: 40px 20px 20px; }
.app.merge-active { max-width: 900px; }
.header { margin-bottom: 24px; }
.header h1 { font-size: 20px; font-weight: 600; margin-bottom: 4px; }
.header p { color: var(--text-dim); font-size: 13px; }
.drop-zone {
border: 1px dashed var(--border);
padding: 32px 20px;
text-align: center;
cursor: pointer;
background: #f9f9f9;
transition: border-color 0.15s;
}
.drop-zone:hover, .drop-zone.drag-over { border-color: var(--accent); }
.drop-zone h3 { font-size: 14px; font-weight: 500; margin-bottom: 4px; color: var(--text); }
.drop-zone p { font-size: 12px; color: var(--text-muted); }
.drop-zone input[type="file"] { display: none; }
.file-section { margin-top: 16px; }
.file-section-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 8px;
padding: 0 2px;
}
.file-count {
font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
font-size: 12px;
color: var(--text-dim);
}
.total-size {
font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
font-size: 11px;
color: var(--text-muted);
}
.file-list { display: flex; flex-direction: column; }
.file-item {
display: flex;
align-items: center;
gap: 10px;
padding: 8px 0;
border-bottom: 1px solid #eee;
}
.file-item:last-child { border-bottom: none; }
.file-ext {
font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
font-size: 10px;
font-weight: 500;
text-transform: uppercase;
padding: 2px 6px;
border-radius: 3px;
background: #f0f0f0;
color: var(--text-dim);
min-width: 40px;
text-align: center;
}
.file-name {
flex: 1;
font-size: 13px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.file-size {
font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
font-size: 11px;
color: var(--text-muted);
flex-shrink: 0;
}
.file-remove {
background: none;
border: none;
color: var(--text-muted);
cursor: pointer;
font-size: 14px;
padding: 2px 6px;
line-height: 1;
}
.file-remove:hover { color: var(--error); }
.clear-all {
background: none;
border: none;
color: var(--text-muted);
font-size: 11px;
cursor: pointer;
}
.clear-all:hover { color: var(--error); }
.controls { margin-top: 20px; display: flex; gap: 10px; align-items: stretch; }
.format-select-wrapper { flex: 1; }
.format-select {
width: 100%;
height: 36px;
padding: 0 32px 0 10px;
background: #fff;
border: 1px solid var(--border);
border-radius: 4px;
color: var(--text);
font-size: 13px;
cursor: pointer;
appearance: none;
transition: border-color 0.15s;
}
.format-select:hover, .format-select:focus { border-color: var(--accent); outline: none; }
.format-select-wrapper { position: relative; }
.format-select-wrapper::after {
content: '';
position: absolute;
right: 12px;
top: 50%;
transform: translateY(-50%);
border: 4px solid transparent;
border-top-color: var(--text-muted);
pointer-events: none;
}
.convert-btn {
padding: 0 20px;
height: 36px;
background: var(--accent);
color: #fff;
border: none;
border-radius: 4px;
font-size: 13px;
font-weight: 500;
cursor: pointer;
white-space: nowrap;
display: flex;
align-items: center;
gap: 8px;
transition: filter 0.15s;
}
.convert-btn:hover:not(:disabled) { filter: brightness(0.9); }
.convert-btn:disabled { opacity: 0.4; cursor: not-allowed; }
.convert-btn.processing { pointer-events: none; }
.convert-btn .spinner {
display: none;
width: 14px;
height: 14px;
border: 2px solid rgba(255,255,255,0.3);
border-top-color: #fff;
border-radius: 50%;
animation: spin 0.6s linear infinite;
}
.convert-btn.processing .spinner { display: block; }
.convert-btn.processing .btn-text { display: none; }
@keyframes spin { to { transform: rotate(360deg); } }
.merge-option {
margin-top: 12px;
font-size: 13px;
display: flex;
align-items: center;
gap: 6px;
}
.merge-option input[type="checkbox"] { margin: 0; }
.merge-panel {
margin-top: 16px;
display: none;
}
.merge-panel.visible { display: block; }
.merge-table-wrap {
overflow-x: auto;
border: 1px solid var(--border);
border-radius: 4px;
}
.merge-table {
width: 100%;
border-collapse: collapse;
font-size: 13px;
min-width: 500px;
}
.merge-table th {
text-align: left;
font-weight: 600;
padding: 8px 10px;
border-bottom: 2px solid var(--border);
background: #f9f9f9;
white-space: nowrap;
}
.merge-table td {
padding: 6px 10px;
border-bottom: 1px solid #eee;
vertical-align: middle;
}
.merge-table tr:last-child td { border-bottom: none; }
.merge-table input[type="text"] {
width: 100%;
min-width: 100px;
border: 1px solid var(--border);
padding: 4px 6px;
font: inherit;
font-size: 12px;
border-radius: 2px;
}
.merge-table input[type="text"]:focus { outline: none; border-color: var(--accent); }
.merge-table select {
font: inherit;
font-size: 12px;
padding: 4px 6px;
border: 1px solid var(--border);
border-radius: 2px;
max-width: 140px;
}
.merge-table select:focus { outline: none; border-color: var(--accent); }
.merge-row-remove {
background: none;
border: none;
color: var(--text-muted);
cursor: pointer;
font-size: 14px;
padding: 2px 6px;
}
.merge-row-remove:hover { color: var(--error); }
.merge-add-col {
background: none;
border: none;
color: var(--text-dim);
cursor: pointer;
font-size: 12px;
padding: 8px 10px;
text-align: left;
}
.merge-add-col:hover { color: var(--accent); }
.merge-note {
margin-top: 8px;
font-size: 11px;
color: var(--text-muted);
}
.progress-container {
margin-top: 16px;
display: none;
}
.progress-container.visible { display: block; }
.progress-bar {
height: 6px;
background: #eee;
border-radius: 3px;
overflow: hidden;
}
.progress-fill {
height: 100%;
background: var(--accent);
width: 0%;
transition: width 0.1s;
}
.progress-text {
margin-top: 6px;
font-size: 12px;
color: var(--text-dim);
font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
}
.results { margin-top: 16px; display: flex; flex-direction: column; gap: 4px; }
.result-item {
display: flex;
align-items: center;
gap: 8px;
padding: 6px 0;
font-size: 12px;
font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
flex-wrap: wrap;
}
.result-item.success { color: var(--success); }
.result-item.error { color: var(--error); }
.result-item.info { color: var(--text-dim); }
.result-icon { flex-shrink: 0; }
.result-from { color: var(--text-dim); }
.result-arrow { color: var(--text-muted); font-size: 10px; }
.result-to { font-weight: 500; }
.result-meta { margin-left: auto; font-size: 10px; opacity: 0.8; flex-shrink: 0; }
.result-error-msg {
margin-left: auto;
font-size: 11px;
max-width: 240px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.test-section {
margin-top: 24px;
padding-top: 16px;
border-top: 1px solid var(--border);
}
.test-section summary {
cursor: pointer;
font-size: 12px;
color: var(--text-muted);
}
.test-section summary:hover { color: var(--text-dim); }
.test-controls {
margin-top: 12px;
display: flex;
gap: 8px;
flex-wrap: wrap;
}
.test-btn {
padding: 6px 12px;
font-size: 11px;
background: #f5f5f5;
border: 1px solid var(--border);
border-radius: 3px;
cursor: pointer;
font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
}
.test-btn:hover { background: #eee; }
.test-results {
margin-top: 12px;
padding: 10px;
background: #f9f9f9;
border-radius: 4px;
font-size: 11px;
font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
white-space: pre-wrap;
max-height: 200px;
overflow-y: auto;
}
footer {
text-align: center;
padding: 40px 0 20px;
font-size: 12px;
color: #999;
}
footer a { color: #999; text-decoration: none; }
footer a:hover { color: #666; text-decoration: underline; }
@media (max-width: 500px) {
.app { padding: 24px 16px 16px; }
.controls { flex-direction: column; }
}
.file-section[data-empty="true"] { display: none; }
</style>
</head>
<body>
<div class="app" id="app">
<header class="header">
<h1>DataForge</h1>
<p>Convert between CSV, Excel, JSON, DBF, DBC and more.</p>
</header>
<div class="drop-zone" id="dropZone">
<h3>Drop files here or click to select</h3>
<p>CSV, TSV, XLSX, XLS, JSON, JSONL, XML, ODS, DBF, DBC</p>
<input type="file" id="fileInput" multiple accept=".csv,.tsv,.xlsx,.xls,.json,.jsonl,.xml,.ods,.txt,.dbf,.dbc">
</div>
<div class="file-section" id="fileSection" data-empty="true">
<div class="file-section-header">
<span class="file-count" id="fileCount">0 files</span>
<span class="total-size" id="totalSize">0 KB / 100 MB</span>
<button class="clear-all" id="clearAll">clear all</button>
</div>
<div class="file-list" id="fileList"></div>
</div>
<div class="controls">
<div class="format-select-wrapper">
<select class="format-select" id="outputFormat">
<optgroup label="Text / Tabular">
<option value="csv">CSV (Comma-Separated)</option>
<option value="tsv">TSV (Tab-Separated)</option>
<option value="xlsx">XLSX (Excel)</option>
<option value="json">JSON (Array of Objects)</option>
<option value="jsonl">JSONL (JSON Lines)</option>
<option value="xml">XML</option>
<option value="md">Markdown Table</option>
<option value="sql">SQL INSERT Statements</option>
</optgroup>
<optgroup label="Legacy / DATASUS">
<option value="dbf">DBF (dBase III)</option>
</optgroup>
</select>
</div>
<button class="convert-btn" id="convertBtn" disabled>
<span class="btn-text">Convert & Download</span>
<span class="spinner"></span>
</button>
</div>
<div class="merge-option">
<input type="checkbox" id="mergeToggle">
<label for="mergeToggle">Merge into single file</label>
</div>
<div class="merge-panel" id="mergePanel">
<div class="merge-table-wrap">
<table class="merge-table" id="mergeTable">
<thead id="mergeTableHead"></thead>
<tbody id="mergeTableBody"></tbody>
</table>
</div>
<button class="merge-add-col" id="mergeAddCol">+ Add column</button>
<p class="merge-note">A "_source_file" column will be added to identify each row's origin.</p>
</div>
<div class="progress-container" id="progressContainer">
<div class="progress-bar"><div class="progress-fill" id="progressFill"></div></div>
<div class="progress-text" id="progressText">Processing...</div>
</div>
<div class="results" id="results"></div>
<details class="test-section">
<summary>Performance Tests</summary>
<div class="test-controls">
<button class="test-btn" data-rows="1000">Test 1K rows</button>
<button class="test-btn" data-rows="10000">Test 10K rows</button>
<button class="test-btn" data-rows="50000">Test 50K rows</button>
<button class="test-btn" data-rows="100000">Test 100K rows</button>
<button class="test-btn" data-rows="300000">Test 300K rows</button>
<button class="test-btn" data-rows="500000">Test 500K rows</button>
<button class="test-btn" data-rows="1000000">Test 1M rows</button>
</div>
<div class="test-results" id="testResults">Click a test button to run performance tests.</div>
</details>
</div>
<footer>
Built by <a href="https://github.com/drgmb" target="_blank" rel="noopener">drgmb</a>
</footer>
<script>
// ═══════════════════════════════════════════════════════════════════
// PROCESSING TIERS - Automatic scaling based on data volume
// ═══════════════════════════════════════════════════════════════════
//
// Tier 1: DIRECT (< 50K rows)
// - Simple synchronous processing
// - Fast, no overhead
//
// Tier 2: CHUNKED (50K - 200K rows)
// - Process in chunks of 10K rows
// - Yield to UI between chunks (setTimeout)
// - Progress bar updates
//
// Tier 3: STREAMING (200K - 1M rows)
// - Generate output in parts, concat to Blob
// - Never hold full string in memory
// - Chunked processing with smaller batches
//
// Tier 4: FILE_SYSTEM (> 1M rows, Chrome/Edge only)
// - Use File System Access API
// - Stream directly to disk
// - Fallback to Tier 3 with warning on other browsers
//
// ═══════════════════════════════════════════════════════════════════
const ProcessingTier = {
DIRECT: { name: 'Direct', maxRows: 50000, chunkSize: null },
CHUNKED: { name: 'Chunked', maxRows: 200000, chunkSize: 10000 },
STREAMING: { name: 'Streaming', maxRows: 1000000, chunkSize: 5000 },
FILE_SYSTEM: { name: 'FileSystem', maxRows: Infinity, chunkSize: 5000 }
};
function getTier(rowCount) {
if (rowCount <= ProcessingTier.DIRECT.maxRows) return ProcessingTier.DIRECT;
if (rowCount <= ProcessingTier.CHUNKED.maxRows) return ProcessingTier.CHUNKED;
if (rowCount <= ProcessingTier.STREAMING.maxRows) return ProcessingTier.STREAMING;
return ProcessingTier.FILE_SYSTEM;
}
function supportsFileSystemAPI() {
return 'showSaveFilePicker' in window;
}
// Yield to UI
function yieldToUI() {
return new Promise(resolve => setTimeout(resolve, 0));
}
// ═══════════════════════════════════════════════════════════════════
// BLAST DECOMPRESSOR
// ═══════════════════════════════════════════════════════════════════
const Blast = (function() {
'use strict';
const MAXBITS = 13, MAXWIN = 4096;
const BASE = [3,2,4,5,6,7,8,9,10,12,16,24,40,72,136,264];
const EXTRA = [0,0,0,0,0,0,0,0,1,2,3,4,5,6,7,8];
const LITLEN_COMPACT = [11,124,8,7,28,7,188,13,76,4,10,8,12,10,12,10,8,23,8,9,7,6,7,8,7,6,55,8,23,24,12,11,7,9,11,12,6,7,22,5,7,24,6,11,9,6,7,22,7,11,38,7,9,8,25,11,8,11,9,12,8,12,5,38,5,38,5,11,7,5,6,21,6,10,53,8,7,24,10,27,44,253,253,253,252,252,252,13,12,45,12,45,12,61,12,45,44,173];
const LENLEN_COMPACT = [2,35,36,53,38,23];
const DISTLEN_COMPACT = [2,20,53,230,247,151,248];
function expand(c) { const o=[]; for(const b of c){const cnt=(b>>4)+1,len=b&0x0F;for(let i=0;i<cnt;i++)o.push(len);} return o; }
function construct(lengths) {
const n=lengths.length,count=new Int32Array(MAXBITS+1),symbol=new Int32Array(n);
for(let i=0;i<n;i++)count[lengths[i]]++;
const offs=new Int32Array(MAXBITS+1);
for(let i=1;i<MAXBITS;i++)offs[i+1]=offs[i]+count[i];
for(let sym=0;sym<n;sym++)if(lengths[sym]!==0)symbol[offs[lengths[sym]]++]=sym;
return {count,symbol};
}
const litcode=construct(expand(LITLEN_COMPACT)),lencode=construct(expand(LENLEN_COMPACT)),distcode=construct(expand(DISTLEN_COMPACT));
function bits(s,need){let val=s.bitbuf;while(s.bitcnt<need){if(s.inpos>=s.input.length)throw new Error('Blast: unexpected end');val|=s.input[s.inpos++]<<s.bitcnt;s.bitcnt+=8;}s.bitbuf=val>>need;s.bitcnt-=need;return val&((1<<need)-1);}
function decode(s,h){let bitbuf=s.bitbuf,left=s.bitcnt,code=0,first=0,index=0,len=1,next=1;while(true){while(left--){code|=(bitbuf&1)^1;bitbuf>>=1;const cnt=h.count[next++];if(code<first+cnt){s.bitbuf=bitbuf;s.bitcnt=(s.bitcnt-len)&7;return h.symbol[index+(code-first)];}index+=cnt;first+=cnt;first<<=1;code<<=1;len++;}left=(MAXBITS+1)-len;if(left===0)break;if(s.inpos>=s.input.length)throw new Error('Blast: unexpected end');bitbuf=s.input[s.inpos++];if(left>8)left=8;}throw new Error('Blast: incomplete code');}
function decompress(input){const s={input,inpos:0,bitbuf:0,bitcnt:0};const lit=bits(s,8),dict=bits(s,8);if(lit>1)throw new Error('Blast: invalid literal');if(dict<4||dict>6)throw new Error('Blast: invalid dict');const win=new Uint8Array(MAXWIN);let wnext=0;const chunks=[];function flush(){if(wnext>0){chunks.push(win.slice(0,wnext));wnext=0;}}while(true){if(bits(s,1)){const sym=decode(s,lencode),len=BASE[sym]+bits(s,EXTRA[sym]);if(len===519)break;const distBits=len===2?2:dict;let dist=decode(s,distcode)<<distBits;dist+=bits(s,distBits);dist++;let rem=len;do{let from,copy;const to=wnext;if(wnext>=dist){from=wnext-dist;copy=MAXWIN-wnext;}else{from=MAXWIN+wnext-dist;copy=dist-wnext;if(copy>MAXWIN-from)copy=MAXWIN-from;}if(copy>rem)copy=rem;rem-=copy;wnext+=copy;for(let i=0;i<copy;i++)win[to+i]=win[from+i];if(wnext===MAXWIN)flush();}while(rem>0);}else{win[wnext++]=lit?decode(s,litcode):bits(s,8);if(wnext===MAXWIN)flush();}}flush();let total=0;for(const c of chunks)total+=c.length;const result=new Uint8Array(total);let off=0;for(const c of chunks){result.set(c,off);off+=c.length;}return result;}
return {decompress};
})();
// ═══════════════════════════════════════════════════════════════════
// DBF PARSER & WRITER
// ═══════════════════════════════════════════════════════════════════
const DBF = (function() {
'use strict';
const dec=new TextDecoder('windows-1252'),enc=new TextEncoder();
function parse(buf){const d=buf instanceof Uint8Array?buf:new Uint8Array(buf);const v=new DataView(d.buffer,d.byteOffset,d.byteLength);if(d.length<32)throw new Error('DBF: file too small');const numRec=v.getUint32(4,true),hdrLen=v.getUint16(8,true),recLen=v.getUint16(10,true);const fields=[];let off=32;while(off+32<=hdrLen&&d[off]!==0x0D){let ne=off;while(ne<off+11&&d[ne]!==0)ne++;const name=dec.decode(d.slice(off,ne)).trim(),type=String.fromCharCode(d[off+11]),flen=d[off+16],fdec=d[off+17];if(name&&flen>0)fields.push({name,type,length:flen,decimal:fdec});off+=32;}if(fields.length===0)throw new Error('DBF: no fields');const records=[];let roff=hdrLen;const max=Math.min(numRec,10000000);for(let r=0;r<max;r++){if(roff+1>d.length)break;const flag=d[roff];if(flag===0x1A)break;roff++;if(flag===0x2A){roff+=recLen-1;continue;}const rec={};for(const f of fields){if(roff+f.length>d.length){roff=d.length;break;}const raw=dec.decode(d.slice(roff,roff+f.length)).trim();roff+=f.length;switch(f.type){case'N':case'F':if(raw===''||/^\*+$/.test(raw))rec[f.name]=null;else{const n=parseFloat(raw);rec[f.name]=isNaN(n)?raw:n;}break;case'L':rec[f.name]='TtYy1'.includes(raw)?true:'FfNn0'.includes(raw)?false:null;break;case'D':rec[f.name]=(raw.length===8&&raw.trim())?raw.slice(0,4)+'-'+raw.slice(4,6)+'-'+raw.slice(6,8):(raw||null);break;default:rec[f.name]=raw;}}records.push(rec);}return{fields,records};}
function write(records){if(!records||!records.length)throw new Error('DBF: no records');const keys=[],ks=new Set();for(const r of records)for(const k of Object.keys(r))if(!ks.has(k)){ks.add(k);keys.push(k);}const fields=keys.map(name=>{let ml=1,allN=true,maxD=0;for(const r of records){const v=r[name];if(v==null||v==='')continue;const s=String(v),bl=enc.encode(s).length;if(bl>ml)ml=bl;if(allN&&isNaN(Number(v)))allN=false;if(allN&&s.includes('.')){const dd=(s.split('.')[1]||'').length;if(dd>maxD)maxD=dd;}}if(allN&&ml<=18)return{name:name.slice(0,10),type:'N',length:Math.min(Math.max(ml,maxD+2,1),18),decimal:Math.min(maxD,15),src:name};return{name:name.slice(0,10),type:'C',length:Math.min(Math.max(ml,1),254),decimal:0,src:name};});const hLen=32+fields.length*32+1,rLen=1+fields.reduce((s,f)=>s+f.length,0);const buf=new Uint8Array(hLen+records.length*rLen+1),dv=new DataView(buf.buffer);const now=new Date();buf[0]=0x03;buf[1]=now.getFullYear()-1900;buf[2]=now.getMonth()+1;buf[3]=now.getDate();dv.setUint32(4,records.length,true);dv.setUint16(8,hLen,true);dv.setUint16(10,rLen,true);let o=32;for(const f of fields){buf.set(enc.encode(f.name).slice(0,11),o);buf[o+11]=f.type.charCodeAt(0);buf[o+16]=f.length;buf[o+17]=f.decimal;o+=32;}buf[o]=0x0D;let ro=hLen;for(const rec of records){buf[ro++]=0x20;for(const f of fields){let v=rec[f.src];if(v==null)v='';let s=String(v);s=f.type==='N'?s.slice(0,f.length).padStart(f.length,' '):s.slice(0,f.length).padEnd(f.length,' ');const bytes=enc.encode(s);for(let i=0;i<f.length;i++)buf[ro+i]=i<bytes.length?bytes[i]:0x20;ro+=f.length;}}buf[ro]=0x1A;return buf;}
return {parse,write};
})();
// ═══════════════════════════════════════════════════════════════════
// DBC (DATASUS)
// ═══════════════════════════════════════════════════════════════════
const DBC = (function() {
'use strict';
function parse(data){const buf=data instanceof Uint8Array?data:new Uint8Array(data);if(buf.length<32)throw new Error('DBC: file too small');const view=new DataView(buf.buffer,buf.byteOffset,buf.byteLength),headerLen=view.getUint16(8,true);if(headerLen<32||headerLen>buf.length-4)throw new Error('DBC: invalid header');const compressedStart=headerLen+4;if(compressedStart>=buf.length)throw new Error('DBC: no compressed data');const compressed=buf.slice(compressedStart),decompressed=Blast.decompress(compressed),header=buf.slice(0,headerLen),dbfBuf=new Uint8Array(header.length+decompressed.length);dbfBuf.set(header);dbfBuf.set(decompressed,header.length);return DBF.parse(dbfBuf);}
return {parse};
})();
// ═══════════════════════════════════════════════════════════════════
// MAIN APPLICATION
// ═══════════════════════════════════════════════════════════════════
(function() {
'use strict';
let files = [];
let parsedFiles = [];
let mergeMapping = [];
const MAX = 100 * 1024 * 1024;
const SUP = new Set(['csv','tsv','xlsx','xls','json','jsonl','xml','ods','txt','dbf','dbc']);
const $ = id => document.getElementById(id);
const appEl = $('app');
const dropZone = $('dropZone'), fileInput = $('fileInput'), fileSection = $('fileSection');
const fileList = $('fileList'), fileCount = $('fileCount'), totalSizeEl = $('totalSize');
const clearAll = $('clearAll'), outputFmt = $('outputFormat');
const convertBtn = $('convertBtn'), resultsEl = $('results');
const mergeToggle = $('mergeToggle'), mergePanel = $('mergePanel');
const mergeTableHead = $('mergeTableHead'), mergeTableBody = $('mergeTableBody');
const mergeAddCol = $('mergeAddCol');
const progressContainer = $('progressContainer'), progressFill = $('progressFill'), progressText = $('progressText');
const testResults = $('testResults');
const fmtB = b => b < 1024 ? b+' B' : b < 1048576 ? (b/1024).toFixed(1)+' KB' : (b/1048576).toFixed(1)+' MB';
const ext = n => (n.split('.').pop()||'').toLowerCase();
const base = n => { const p = n.split('.'); p.pop(); return p.join('.')||n; };
// ── Progress helpers ──
function showProgress(pct, text) {
progressContainer.classList.add('visible');
progressFill.style.width = pct + '%';
progressText.textContent = text;
}
function hideProgress() {
progressContainer.classList.remove('visible');
}
// ── Column matching ──
function norm(name) {
return name.normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[-\s_.]+/g, '').toLowerCase(); // fix: removed no-op camelCase split
}
function dice(a, b) {
if (a.length < 2 || b.length < 2) return a === b ? 1 : 0;
const bg = s => { const m = new Map(); for (let i = 0; i < s.length - 1; i++) { const g = s.slice(i, i + 2); m.set(g, (m.get(g) || 0) + 1); } return m; };
const A = bg(a), B = bg(b); let inter = 0;
for (const [k, v] of A) inter += Math.min(v, B.get(k) || 0);
const total = a.length + b.length - 2;
return total === 0 ? 0 : (2 * inter) / total;
}
function autoMatch(filesData) {
const allCols = [];
filesData.forEach((fd, fi) => { fd.headers.forEach(col => { allCols.push({ fileIdx: fi, fileName: fd.file.name, colName: col, normName: norm(col) }); }); });
const parent = allCols.map((_, i) => i);
const find = i => parent[i] === i ? i : (parent[i] = find(parent[i]));
const union = (i, j) => { parent[find(i)] = find(j); };
for (let i = 0; i < allCols.length; i++) for (let j = i + 1; j < allCols.length; j++) if (allCols[i].fileIdx !== allCols[j].fileIdx && allCols[i].colName.toLowerCase() === allCols[j].colName.toLowerCase()) union(i, j);
for (let i = 0; i < allCols.length; i++) for (let j = i + 1; j < allCols.length; j++) if (allCols[i].fileIdx !== allCols[j].fileIdx && find(i) !== find(j) && allCols[i].normName === allCols[j].normName) union(i, j);
for (let i = 0; i < allCols.length; i++) for (let j = i + 1; j < allCols.length; j++) if (allCols[i].fileIdx !== allCols[j].fileIdx && find(i) !== find(j) && dice(allCols[i].normName, allCols[j].normName) > 0.8) union(i, j);
const groups = new Map();
allCols.forEach((col, i) => { const root = find(i); if (!groups.has(root)) groups.set(root, []); groups.get(root).push(col); });
const mapping = [];
for (const members of groups.values()) {
const names = members.map(m => m.colName);
const outputCol = names.reduce((a, b) => a.length <= b.length ? a : b).toLowerCase();
const sources = {};
for (const m of members) sources[m.fileName] = m.colName;
mapping.push({ outputCol, sources });
}
return mapping;
}
// ── Drop zone ──
dropZone.addEventListener('click', () => fileInput.click());
dropZone.addEventListener('dragover', e => { e.preventDefault(); dropZone.classList.add('drag-over'); });
dropZone.addEventListener('dragleave', () => dropZone.classList.remove('drag-over'));
dropZone.addEventListener('drop', e => { e.preventDefault(); dropZone.classList.remove('drag-over'); add(e.dataTransfer.files); });
fileInput.addEventListener('change', () => { add(fileInput.files); fileInput.value = ''; });
clearAll.addEventListener('click', () => { files = []; parsedFiles = []; mergeMapping = []; render(); updateMergePanel(); resultsEl.innerHTML = ''; });
function add(list) {
for (const f of list) {
if (!SUP.has(ext(f.name))) continue;
if (files.some(x => x.name === f.name && x.size === f.size)) continue;
files.push(f);
}
render();
if (mergeToggle.checked) updateMergePanel();
}
function render() {
const empty = !files.length;
fileSection.setAttribute('data-empty', empty);
convertBtn.disabled = empty;
fileCount.textContent = files.length + ' file' + (files.length !== 1 ? 's' : '');
const tot = files.reduce((s, f) => s + f.size, 0);
totalSizeEl.textContent = fmtB(tot) + ' / 100 MB';
totalSizeEl.style.color = tot > MAX ? 'var(--error)' : '';
if (tot > MAX) convertBtn.disabled = true;
fileList.innerHTML = '';
files.forEach((f, i) => {
const e = ext(f.name);
const d = document.createElement('div');
d.className = 'file-item';
d.innerHTML = `<span class="file-ext">${escHtml(e)}</span><span class="file-name" title="${escHtml(f.name)}">${escHtml(f.name)}</span><span class="file-size">${fmtB(f.size)}</span><button class="file-remove" data-i="${i}">×</button>`; // fix: XSS via filename
fileList.appendChild(d);
});
fileList.querySelectorAll('.file-remove').forEach(b => b.addEventListener('click', () => { files.splice(+b.dataset.i, 1); parsedFiles = parsedFiles.filter(pf => files.some(f => f.name === pf.file.name)); render(); if (mergeToggle.checked) updateMergePanel(); }));
}
// ── Merge toggle ──
mergeToggle.addEventListener('change', () => {
if (mergeToggle.checked) { appEl.classList.add('merge-active'); updateMergePanel(); }
else { appEl.classList.remove('merge-active'); mergePanel.classList.remove('visible'); }
});
async function updateMergePanel() {
if (!mergeToggle.checked || files.length < 2) { mergePanel.classList.remove('visible'); return; }
const needParse = files.filter(f => !parsedFiles.some(pf => pf.file.name === f.name && pf.file.size === f.size));
for (const f of needParse) {
try {
const buf = await readFile(f);
const data = parseInput(buf, ext(f.name));
parsedFiles.push({ file: f, headers: data.headers, objRows: data.objRows });
} catch (err) { console.error('Parse failed', f.name, err); }
}
parsedFiles = parsedFiles.filter(pf => files.some(f => f.name === pf.file.name && f.size === pf.file.size));
if (parsedFiles.length < 2) { mergePanel.classList.remove('visible'); return; }
mergeMapping = autoMatch(parsedFiles);
renderMergeTable();
mergePanel.classList.add('visible');
}
function renderMergeTable() {
const fileNames = parsedFiles.map(pf => pf.file.name);
mergeTableHead.innerHTML = '<tr><th>Output column</th>' + fileNames.map(n => `<th title="${n}">${n.length > 15 ? n.slice(0, 12) + '...' : n}</th>`).join('') + '<th></th></tr>';
mergeTableBody.innerHTML = '';
mergeMapping.forEach((m, rowIdx) => {
const tr = document.createElement('tr');
let html = `<td><input type="text" value="${escHtml(m.outputCol)}" data-row="${rowIdx}" class="merge-out-col"></td>`;
fileNames.forEach(fn => {
const pf = parsedFiles.find(p => p.file.name === fn);
const cols = pf ? pf.headers : [];
const selected = m.sources[fn] || '';
html += '<td><select data-row="' + rowIdx + '" data-file="' + escHtml(fn) + '" class="merge-file-col"><option value="">—</option>';
cols.forEach(c => { html += `<option value="${escHtml(c)}"${c === selected ? ' selected' : ''}>${escHtml(c)}</option>`; });
html += '</select></td>';
});
html += `<td><button class="merge-row-remove" data-row="${rowIdx}">×</button></td>`;
tr.innerHTML = html;
mergeTableBody.appendChild(tr);
});
mergeTableBody.querySelectorAll('.merge-out-col').forEach(inp => { inp.addEventListener('input', e => { mergeMapping[+e.target.dataset.row].outputCol = e.target.value; }); });
mergeTableBody.querySelectorAll('.merge-file-col').forEach(sel => { sel.addEventListener('change', e => { const row = +e.target.dataset.row, file = e.target.dataset.file; if (e.target.value) mergeMapping[row].sources[file] = e.target.value; else delete mergeMapping[row].sources[file]; }); });
mergeTableBody.querySelectorAll('.merge-row-remove').forEach(btn => { btn.addEventListener('click', e => { mergeMapping.splice(+e.target.dataset.row, 1); renderMergeTable(); }); });
}
mergeAddCol.addEventListener('click', () => { mergeMapping.push({ outputCol: 'new_column', sources: {} }); renderMergeTable(); });
function escHtml(s) { return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"'); }
// ── File reading ──
const readFile = f => new Promise((ok, fail) => {
const r = new FileReader();
r.onload = () => ok(r.result);
r.onerror = () => fail(new Error('Failed to read: ' + f.name));
r.readAsArrayBuffer(f);
});
function parseInput(buf, e) {
if (e === 'dbc') { const { fields, records } = DBC.parse(buf); const h = fields.map(f => f.name); return { headers: h, rows: records.map(r => h.map(k => r[k] ?? '')), objRows: records }; }
if (e === 'dbf') { const { fields, records } = DBF.parse(buf); const h = fields.map(f => f.name); return { headers: h, rows: records.map(r => h.map(k => r[k] ?? '')), objRows: records }; }
if (e === 'jsonl') { const t = new TextDecoder('utf-8').decode(buf); const d = t.trim().split('\n').filter(l => l.trim()).map((l, i) => { try { return JSON.parse(l); } catch { throw new Error('JSONL: invalid line ' + (i + 1)); } }); if (!d.length) throw new Error('JSONL is empty'); return s2i(XLSX.utils.json_to_sheet(d)); }
if (e === 'json') { let p = JSON.parse(new TextDecoder('utf-8').decode(buf)); if (!Array.isArray(p)) { if (p === null || typeof p !== 'object') throw new Error('JSON: expected an array or object at root'); /* fix: guard primitive/null root */ const k = Object.keys(p).find(k => Array.isArray(p[k])); p = k ? p[k] : [p]; } if (!p.length) throw new Error('JSON is empty'); return s2i(XLSX.utils.json_to_sheet(p)); }
const opts = { type: 'array', raw: true, cellDates: true };
if (e === 'csv' || e === 'txt') opts.FS = ',';
if (e === 'tsv') opts.FS = '\t';
const wb = XLSX.read(new Uint8Array(buf), opts);
if (!wb.SheetNames.length) throw new Error('No sheets found');
return s2i(wb.Sheets[wb.SheetNames[0]]);
}
function s2i(ws) {
const raw = XLSX.utils.sheet_to_json(ws, { header: 1, raw: true, defval: '' });
const h = (raw[0] || []).map(String);
return {
headers: h,
rows: raw.slice(1),
get objRows() { return XLSX.utils.sheet_to_json(ws, { raw: true, defval: '' }); } // fix: lazy — avoids double parse
};
}
// ═══════════════════════════════════════════════════════════════════
// TIERED OUTPUT GENERATION
// ═══════════════════════════════════════════════════════════════════
// Convert row to CSV line
function rowToCSV(row, sep = ',') {
return row.map(v => {
const s = String(v ?? '');
if (s.includes(sep) || s.includes('"') || s.includes('\n')) return '"' + s.replace(/"/g, '""') + '"';
return s;
}).join(sep) + '\n';
}
// Tier 1: Direct (small datasets)
function generateOutputDirect(headers, rows, fmt, outputName) {
if (fmt === 'csv' || fmt === 'tsv') {
const sep = fmt === 'csv' ? ',' : '\t';
let content = rowToCSV(headers, sep);
for (const row of rows) content += rowToCSV(row, sep);
return new Blob([content], { type: fmt === 'csv' ? 'text/csv' : 'text/tab-separated-values' });
}
if (fmt === 'json' || fmt === 'jsonl' || fmt === 'xml') {
const recs = rows.map(r => { const o = {}; headers.forEach((h, i) => o[h] = r[i] ?? ''); return o; });
if (fmt === 'json') return new Blob([JSON.stringify(recs, null, 2)], { type: 'application/json' });
if (fmt === 'jsonl') return new Blob([recs.map(r => JSON.stringify(r)).join('\n')], { type: 'application/x-jsonlines' });
let x = '<?xml version="1.0" encoding="UTF-8"?>\n<records>\n';
for (const row of recs) { x += ' <record>\n'; for (const [k, v] of Object.entries(row)) { const tag = String(k).replace(/[^a-zA-Z0-9_]/g, '_').replace(/^(\d)/, '_$1'); x += ' <' + tag + '>' + String(v ?? '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>') + '</' + tag + '>\n'; } x += ' </record>\n'; }
return new Blob([x + '</records>'], { type: 'application/xml' });
}
if (fmt === 'md') {
if (!headers.length) return new Blob(['*(empty)*'], { type: 'text/markdown' });
let md = '| ' + headers.join(' | ') + ' |\n| ' + headers.map(() => '---').join(' | ') + ' |\n';
for (const r of rows) md += '| ' + headers.map((_, i) => String(r[i] ?? '').replace(/\|/g, '\\|')).join(' | ') + ' |\n';
return new Blob([md], { type: 'text/markdown' });
}
if (fmt === 'sql') {
const tbl = outputName.replace(/[^a-zA-Z0-9_]/g, '_');
const cols = headers.map(h => '"' + String(h).replace(/"/g, '""') + '"');
let sql = '-- DataForge\n-- Table: ' + tbl + '\n\n';
for (const r of rows) {
const vals = headers.map((_, i) => { const v = r[i]; if (v == null || v === '') return 'NULL'; if (v instanceof Date) return "'" + v.toISOString() + "'"; if (typeof v === 'number') return v; return "'" + String(v).replace(/'/g, "''") + "'"; });
sql += 'INSERT INTO "' + tbl + '" (' + cols.join(', ') + ') VALUES (' + vals.join(', ') + ');\n';
}
return new Blob([sql], { type: 'application/sql' });
}
if (fmt === 'xlsx') {
const ws = XLSX.utils.aoa_to_sheet([headers, ...rows]);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
const b = XLSX.write(wb, { type: 'array', bookType: 'xlsx' });
return new Blob([b], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
}
if (fmt === 'dbf') {
const recs = rows.map(r => { const o = {}; headers.forEach((h, i) => o[h] = r[i] ?? ''); return o; });
return new Blob([DBF.write(recs)], { type: 'application/x-dbf' });
}
throw new Error('Unsupported format: ' + fmt);
}
// Tier 2/3: Chunked/Streaming (medium/large datasets)
async function generateOutputChunked(headers, rows, fmt, outputName, onProgress) {
const totalRows = rows.length;
const tier = getTier(totalRows);
const chunkSize = tier.chunkSize || 5000;
if (fmt === 'csv' || fmt === 'tsv') {
const sep = fmt === 'csv' ? ',' : '\t';
const parts = [rowToCSV(headers, sep)];
for (let i = 0; i < totalRows; i += chunkSize) {
const chunk = rows.slice(i, i + chunkSize);
let chunkStr = '';
for (const row of chunk) chunkStr += rowToCSV(row, sep);
parts.push(chunkStr);
onProgress(Math.min(100, Math.round((i + chunkSize) / totalRows * 100)), `Processing rows ${i + 1}-${Math.min(i + chunkSize, totalRows)} of ${totalRows}...`);
await yieldToUI();
}
return new Blob(parts, { type: fmt === 'csv' ? 'text/csv' : 'text/tab-separated-values' });
}
if (fmt === 'jsonl') {
const parts = [];
for (let i = 0; i < totalRows; i += chunkSize) {
const chunk = rows.slice(i, i + chunkSize);
let chunkStr = '';
for (const row of chunk) {
const obj = {}; headers.forEach((h, j) => obj[h] = row[j] ?? '');
chunkStr += JSON.stringify(obj) + '\n';
}
parts.push(chunkStr);
onProgress(Math.min(100, Math.round((i + chunkSize) / totalRows * 100)), `Processing rows ${i + 1}-${Math.min(i + chunkSize, totalRows)} of ${totalRows}...`);
await yieldToUI();
}
return new Blob(parts, { type: 'application/x-jsonlines' });
}
if (fmt === 'json') {
const parts = ['[\n'];
let first = true;
for (let i = 0; i < totalRows; i += chunkSize) {
const chunk = rows.slice(i, i + chunkSize);
let chunkStr = '';
for (const row of chunk) {
const obj = {}; headers.forEach((h, j) => obj[h] = row[j] ?? '');
chunkStr += (first ? '' : ',\n') + JSON.stringify(obj);
first = false;
}
parts.push(chunkStr);
onProgress(Math.min(100, Math.round((i + chunkSize) / totalRows * 100)), `Processing rows ${i + 1}-${Math.min(i + chunkSize, totalRows)} of ${totalRows}...`);
await yieldToUI();
}
parts.push('\n]');
return new Blob(parts, { type: 'application/json' });
}
if (fmt === 'xml') {
const parts = ['<?xml version="1.0" encoding="UTF-8"?>\n<records>\n'];
for (let i = 0; i < totalRows; i += chunkSize) {
const chunk = rows.slice(i, i + chunkSize);
let chunkStr = '';
for (const row of chunk) {
chunkStr += ' <record>\n';
headers.forEach((h, j) => {
const tag = String(h).replace(/[^a-zA-Z0-9_]/g, '_').replace(/^(\d)/, '_$1');
const v = String(row[j] ?? '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
chunkStr += ' <' + tag + '>' + v + '</' + tag + '>\n';
});
chunkStr += ' </record>\n';
}
parts.push(chunkStr);
onProgress(Math.min(100, Math.round((i + chunkSize) / totalRows * 100)), `Processing rows ${i + 1}-${Math.min(i + chunkSize, totalRows)} of ${totalRows}...`);
await yieldToUI();
}
parts.push('</records>');
return new Blob(parts, { type: 'application/xml' });
}
if (fmt === 'sql') {
const tbl = outputName.replace(/[^a-zA-Z0-9_]/g, '_');
const cols = headers.map(h => '"' + String(h).replace(/"/g, '""') + '"');
const parts = ['-- DataForge\n-- Table: ' + tbl + '\n\n'];
for (let i = 0; i < totalRows; i += chunkSize) {
const chunk = rows.slice(i, i + chunkSize);
let chunkStr = '';
for (const row of chunk) {
const vals = headers.map((_, j) => { const v = row[j]; if (v == null || v === '') return 'NULL'; if (typeof v === 'number') return v; return "'" + String(v).replace(/'/g, "''") + "'"; });
chunkStr += 'INSERT INTO "' + tbl + '" (' + cols.join(', ') + ') VALUES (' + vals.join(', ') + ');\n';
}
parts.push(chunkStr);
onProgress(Math.min(100, Math.round((i + chunkSize) / totalRows * 100)), `Processing rows ${i + 1}-${Math.min(i + chunkSize, totalRows)} of ${totalRows}...`);
await yieldToUI();
}
return new Blob(parts, { type: 'application/sql' });
}
if (fmt === 'md') {
const parts = [];
parts.push('| ' + headers.join(' | ') + ' |\n| ' + headers.map(() => '---').join(' | ') + ' |\n');
for (let i = 0; i < totalRows; i += chunkSize) {
const chunk = rows.slice(i, i + chunkSize);
let chunkStr = '';
for (const row of chunk) chunkStr += '| ' + headers.map((_, j) => String(row[j] ?? '').replace(/\|/g, '\\|')).join(' | ') + ' |\n';
parts.push(chunkStr);
onProgress(Math.min(100, Math.round((i + chunkSize) / totalRows * 100)), `Processing rows ${i + 1}-${Math.min(i + chunkSize, totalRows)} of ${totalRows}...`);
await yieldToUI();
}
return new Blob(parts, { type: 'text/markdown' });
}
// XLSX: Split into 50K row files to avoid browser memory issues
if (fmt === 'xlsx') {
const XLSX_MAX_ROWS = 50000;
// Single file if <= 50K rows
if (totalRows <= XLSX_MAX_ROWS) {
onProgress(5, 'Creating XLSX worksheet...');
await yieldToUI();
const ws = XLSX.utils.aoa_to_sheet([headers]);
const xlsxChunkSize = Math.min(chunkSize, 2000);
for (let i = 0; i < totalRows; i += xlsxChunkSize) {
const end = Math.min(i + xlsxChunkSize, totalRows);
XLSX.utils.sheet_add_aoa(ws, rows.slice(i, end), { origin: i + 1 });
onProgress(5 + Math.round((i / totalRows) * 70), `Adding rows ${i + 1}-${end}...`);
await yieldToUI();
}
onProgress(85, 'Generating XLSX...');
await yieldToUI();
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
const b = XLSX.write(wb, { type: 'array', bookType: 'xlsx' });
return new Blob([b], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
}
// Multiple files for > 50K rows
const numParts = Math.ceil(totalRows / XLSX_MAX_ROWS);
const xlsxParts = [];
for (let part = 0; part < numParts; part++) {
const startRow = part * XLSX_MAX_ROWS;
const endRow = Math.min(startRow + XLSX_MAX_ROWS, totalRows);
const partRows = rows.slice(startRow, endRow);
onProgress(Math.round((part / numParts) * 90), `Creating XLSX part ${part + 1}/${numParts} (rows ${startRow + 1}-${endRow})...`);
await yieldToUI();
const ws = XLSX.utils.aoa_to_sheet([headers]);
const xlsxChunkSize = 2000;
for (let i = 0; i < partRows.length; i += xlsxChunkSize) {
const end = Math.min(i + xlsxChunkSize, partRows.length);
XLSX.utils.sheet_add_aoa(ws, partRows.slice(i, end), { origin: i + 1 });
await yieldToUI();
}
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
const b = XLSX.write(wb, { type: 'array', bookType: 'xlsx' });
xlsxParts.push({
name: outputName + '_part' + (part + 1) + '.xlsx',
blob: new Blob([b], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }),
rows: partRows.length
});
}
// Return array of parts (caller must handle this)
return { split: true, parts: xlsxParts, totalRows, numParts };
}
// DBF: Build records incrementally
if (fmt === 'dbf') {
// DBF practical limit ~1M rows due to memory constraints
if (totalRows > 1000000) {
throw new Error('DBF format limited to ~1M rows for performance. Use CSV for larger datasets.');
}
onProgress(10, 'Building DBF records...');
await yieldToUI();
// Build records using simple object creation
const recs = new Array(totalRows);
for (let i = 0; i < totalRows; i += chunkSize) {
const end = Math.min(i + chunkSize, totalRows);
for (let ri = i; ri < end; ri++) {
const row = rows[ri];
const obj = {};
for (let c = 0; c < headers.length; c++) {
obj[headers[c]] = row[c] ?? '';
}
recs[ri] = obj;
}
onProgress(10 + Math.round((i / totalRows) * 60), `Processing rows ${i + 1}-${end} of ${totalRows}...`);
await yieldToUI();
}
onProgress(75, 'Generating DBF file...');
await yieldToUI();
const result = new Blob([DBF.write(recs)], { type: 'application/x-dbf' });
// Clear recs to free memory
recs.length = 0;