Open History to see the last commit
1import { GENERIC_MIME_TYPES } from "./image.ts";
2
3export function filePreviewDelimiter(file: { name: string; mimeType?: string }): "," | "\t" | null {
4 const mime = file.mimeType?.split(";", 1)[0]?.trim().toLowerCase();
5 if (mime === "text/csv") return ",";
6 if (mime === "text/tab-separated-values") return "\t";
7 if (mime && mime !== "text/plain" && !GENERIC_MIME_TYPES.has(mime)) return null;
8 if (/\.csv$/i.test(file.name)) return ",";
9 if (/\.tsv$/i.test(file.name)) return "\t";
10 return null;
11}
12
13export function parseDelimitedPreview(
14 text: string,
15 delimiter: "," | ";" | "\t",
16 {
17 maxRows = 100,
18 maxColumns = 30,
19 maxCellLength = 2000,
20 detectCsv = true,
21 stripBom = true,
22 inputComplete = true,
23 }: {
24 maxRows?: number;
25 maxColumns?: number;
26 maxCellLength?: number;
27 detectCsv?: boolean;
28 stripBom?: boolean;
29 inputComplete?: boolean;
30 } = {},
31) {
32 if (delimiter === "," && detectCsv) {
33 const detector = createCsvPreviewDetector({ stripBom });
34 delimiter = detector.push(text) ?? detector.finish(inputComplete);
35 }
36 const rows: string[][] = [];
37 let row: string[] = [];
38 let cell = "";
39 let quoted = false;
40 let truncated = false;
41 let rowStart = stripBom && text.charCodeAt(0) === 0xfeff ? 1 : 0;
42 // At the start of a file, skip blank lines so the first nonempty record is the header.
43 // Worker pages pass stripBom: false and can start on an interior blank record.
44 while (stripBom && (text[rowStart] === "\r" || text[rowStart] === "\n")) rowStart++;
45 const endCell = () => {
46 if (cell.length > maxCellLength) {
47 let end = maxCellLength;
48 const before = cell.charCodeAt(end - 1);
49 const after = cell.charCodeAt(end);
50 if (before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff) end--;
51 cell = cell.slice(0, end);
52 truncated = true;
53 }
54 if (row.length < maxColumns) row.push(cell);
55 else truncated = true;
56 cell = "";
57 };
58 for (let index = rowStart; index < text.length; index++) {
59 const char = text[index];
60 if (char === '"') {
61 if (quoted && text[index + 1] === '"') {
62 if (cell.length <= maxCellLength) cell += '"';
63 else truncated = true;
64 index++;
65 continue;
66 }
67 if (quoted || cell === "") {
68 quoted = !quoted;
69 continue;
70 }
71 }
72 if (!quoted && (char === delimiter || char === "\n" || char === "\r")) {
73 endCell();
74 if (char !== delimiter) {
75 rows.push(row);
76 row = [];
77 if (char === "\r" && text[index + 1] === "\n") index++;
78 rowStart = index + 1;
79 if (rows.length === maxRows)
80 return { rows, truncated: truncated || index < text.length - 1 };
81 }
82 } else if (cell.length <= maxCellLength) cell += char;
83 else truncated = true;
84 }
85 if (rowStart < text.length) {
86 endCell();
87 rows.push(row);
88 }
89 return { rows, truncated: truncated || quoted };
90}
91
92// Push text until a delimiter is returned, or finish at the end of the sample. Records are
93// compared with the header until one tells the two delimiters apart; a lasting tie keeps commas.
94export function createCsvPreviewDetector({ stripBom = true } = {}) {
95 let headerCommas = 0;
96 let headerSemicolons = 0;
97 let commas = 0;
98 let semicolons = 0;
99 let inHeader = true;
100 let dataRecords = 0;
101 let hasContent = false;
102 let quote: "plain" | "quoted" | "closed" = "plain";
103 let quotedRecordStart = false;
104 let fieldStart = true;
105 let afterCr = false;
106 let first = true;
107
108 function endRecord(): "," | ";" | undefined {
109 const content = hasContent;
110 const recordCommas = commas;
111 const recordSemicolons = semicolons;
112 hasContent = false;
113 commas = 0;
114 semicolons = 0;
115 if (!content) return;
116 if (inHeader) {
117 inHeader = false;
118 headerCommas = recordCommas;
119 headerSemicolons = recordSemicolons;
120 return headerSemicolons === 0 ? "," : undefined;
121 }
122 dataRecords++;
123 if (recordSemicolons !== headerSemicolons) return ",";
124 if (headerCommas === 0 || recordCommas !== headerCommas) return ";";
125 }
126
127 return {
128 push(text: string): "," | ";" | undefined {
129 if (text.length === 0) return;
130 const start = first && stripBom && text.charCodeAt(0) === 0xfeff ? 1 : 0;
131 first = false;
132 for (let index = start; index < text.length; index++) {
133 const char = text[index];
134 if (afterCr) {
135 afterCr = false;
136 if (char === "\n") continue;
137 }
138 if (quote === "quoted") {
139 hasContent = true;
140 if (char === '"') quote = "closed";
141 continue;
142 }
143 if (quote === "closed") {
144 if (char === '"') {
145 quote = "quoted";
146 continue;
147 }
148 quote = "plain";
149 // A record's first field is quoted under either delimiter, so what follows its close decides.
150 if (quotedRecordStart) {
151 quotedRecordStart = false;
152 if (char === "," || char === ";") return char;
153 }
154 }
155 if (char === "\n" || char === "\r") {
156 const delimiter = endRecord();
157 if (delimiter !== undefined) return delimiter;
158 afterCr = char === "\r";
159 fieldStart = true;
160 continue;
161 }
162 const recordStart = !hasContent;
163 hasContent = true;
164 if (char === '"' && fieldStart) {
165 quote = "quoted";
166 quotedRecordStart = recordStart;
167 } else if (char === ",") commas++;
168 else if (char === ";") semicolons++;
169 fieldStart = char === "," || char === ";";
170 }
171 },
172 finish(inputComplete: boolean): "," | ";" {
173 if (inputComplete && (inHeader || hasContent) && quote !== "quoted") {
174 const delimiter = endRecord();
175 if (delimiter !== undefined) return delimiter;
176 }
177 if (dataRecords > 0 || inHeader) return ",";
178 if (inputComplete) return headerSemicolons > headerCommas ? ";" : ",";
179 // Trust a comma-free header unless the partial record already rules it out.
180 return headerCommas === 0 && semicolons <= headerSemicolons ? ";" : ",";
181 },
182 };
183}