Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

delimitedPreview.ts

63 lines2.0 KB

1export function filePreviewDelimiter(file: { name: string; mimeType?: string }): "," | "\t" | null {
2 const mime = file.mimeType?.split(";", 1)[0]?.trim().toLowerCase();
3 if (mime === "text/csv") return ",";
4 if (mime === "text/tab-separated-values") return "\t";
5 if (mime && mime !== "text/plain" && mime !== "application/octet-stream") return null;
6 if (/\.csv$/i.test(file.name)) return ",";
7 if (/\.tsv$/i.test(file.name)) return "\t";
8 return null;
9}
10​
11export function parseDelimitedPreview(
12 text: string,
13 delimiter: "," | "\t",
14 limits: { maxRows: number; maxColumns: number; maxCellLength: number } = {
15 maxRows: 100,
16 maxColumns: 30,
17 maxCellLength: 2000,
18 },
19) {
20 const rows: string[][] = [];
21 let row: string[] = [];
22 let cell = "";
23 let quoted = false;
24 let truncated = false;
25 let rowStart = text.charCodeAt(0) === 0xfeff ? 1 : 0;
26 const endCell = () => {
27 if (row.length < limits.maxColumns) row.push(cell);
28 else truncated = true;
29 cell = "";
30 };
31 for (let index = rowStart; index < text.length; index++) {
32 const char = text[index];
33 if (char === '"') {
34 if (quoted && text[index + 1] === '"') {
35 if (cell.length < limits.maxCellLength) cell += '"';
36 else truncated = true;
37 index++;
38 continue;
39 }
40 if (quoted || cell === "") {
41 quoted = !quoted;
42 continue;
43 }
44 }
45 if (!quoted && (char === delimiter || char === "\n" || char === "\r")) {
46 endCell();
47 if (char !== delimiter) {
48 rows.push(row);
49 row = [];
50 if (char === "\r" && text[index + 1] === "\n") index++;
51 rowStart = index + 1;
52 if (rows.length === limits.maxRows)
53 return { rows, truncated: truncated || index < text.length - 1 };
54 }
55 } else if (cell.length < limits.maxCellLength) cell += char;
56 else truncated = true;
57 }
58 if (rowStart < text.length) {
59 endCell();
60 rows.push(row);
61 }
62 return { rows, truncated: truncated || quoted };