Open History to see the last commit
1import { describe, expect, it } from "vite-plus/test";
2import {
3 createCsvPreviewDetector,
4 filePreviewDelimiter,
5 parseDelimitedPreview,
6} from "./delimitedPreview.ts";
7
8describe("delimited file previews", () => {
9 it("falls back to the file name under generic MIME types", () => {
10 expect(filePreviewDelimiter({ name: "a.csv", mimeType: "binary/octet-stream" })).toBe(",");
11 expect(filePreviewDelimiter({ name: "a.tsv", mimeType: "application/unknown" })).toBe("\t");
12 });
13 it("preserves quoted separators, escaped quotes, blank cells and line breaks", () => {
14 expect(
15 parseDelimitedPreview('\ufeffname,notes,empty\r\n"A, B","say ""hi""\nagain",\r\n', ","),
16 ).toEqual({
17 rows: [
18 ["name", "notes", "empty"],
19 ["A, B", 'say "hi"\nagain', ""],
20 ],
21 truncated: false,
22 });
23 expect(parseDelimitedPreview("one\ttwo\n\tthree", "\t").rows).toEqual([
24 ["one", "two"],
25 ["", "three"],
26 ]);
27 });
28 it("detects semicolon-separated CSV from its first records outside quotes", () => {
29 expect(parseDelimitedPreview("Mass, kg;Count\n5;2", ",").rows).toEqual([
30 ["Mass, kg", "Count"],
31 ["5", "2"],
32 ]);
33 expect(parseDelimitedPreview("a;b\r\n1;2,5", ",").rows).toEqual([
34 ["a", "b"],
35 ["1", "2,5"],
36 ]);
37 expect(parseDelimitedPreview('name,notes\nAlice,"a;b;c"', ",").rows).toEqual([
38 ["name", "notes"],
39 ["Alice", "a;b;c"],
40 ]);
41 expect(parseDelimitedPreview('"a, b";notes\nAlice;"say ""hi""\nagain"', ",").rows).toEqual([
42 ["a, b", "notes"],
43 ["Alice", 'say "hi"\nagain'],
44 ]);
45 expect(parseDelimitedPreview("a,b;c", ",").rows).toEqual([["a", "b;c"]]);
46 expect(parseDelimitedPreview("id,notes;more;extra\n1,plain\n2,ordinary", ",").rows).toEqual([
47 ["id", "notes;more;extra"],
48 ["1", "plain"],
49 ["2", "ordinary"],
50 ]);
51 expect(
52 parseDelimitedPreview("id,notes;more;extra\n1,plain;other;last\n2,ordinary;next;end", ",")
53 .rows,
54 ).toEqual([
55 ["id", "notes;more;extra"],
56 ["1", "plain;other;last"],
57 ["2", "ordinary;next;end"],
58 ]);
59 expect(parseDelimitedPreview('12",name\n24",a;b;c', ",").rows).toEqual([
60 ['12"', "name"],
61 ['24"', "a;b;c"],
62 ]);
63 expect(parseDelimitedPreview("a;b\tvalue", "\t").rows).toEqual([["a;b", "value"]]);
64 expect(parseDelimitedPreview("\ufeff\r\n\r\nItem;Price\r\nBolt;3,5\r\n", ",").rows).toEqual([
65 ["Item", "Price"],
66 ["Bolt", "3,5"],
67 ]);
68 expect(parseDelimitedPreview("\n\nA\tB\n\n1\t2\n", "\t").rows).toEqual([
69 ["A", "B"],
70 [""],
71 ["1", "2"],
72 ]);
73 });
74 it.each([
75 ["inside the header", "Name;Role", ["Name;Role"]],
76 [
77 "inside the second record with a semicolon header",
78 "Name;Role;Team\nDoe",
79 ["Name", "Role", "Team"],
80 ],
81 ["inside the second record with a mixed header", "a;b;c,name\n1", ["a;b;c", "name"]],
82 ["after the second record exceeds the header", "Name;Role;Team\nDoe;a;b;c", ["Name;Role;Team"]],
83 ])("detects the delimiter when a CSV prefix ends %s", (_label, text, header) => {
84 expect(parseDelimitedPreview(text, ",", { inputComplete: false }).rows[0]).toEqual(header);
85 });
86 it("keeps reading CSV records until one tells commas and semicolons apart", () => {
87 expect(
88 parseDelimitedPreview(
89 "Name, full;Role\nDoe, Jane;Engineer\nRoe, Rick;Designer\nPrince;Artist\n",
90 ",",
91 ).rows,
92 ).toEqual([
93 ["Name, full", "Role"],
94 ["Doe, Jane", "Engineer"],
95 ["Roe, Rick", "Designer"],
96 ["Prince", "Artist"],
97 ]);
98 expect(parseDelimitedPreview("a,b;c\n1,2;3\n4,5;6\n7,8", ",").rows.at(-1)).toEqual(["7", "8"]);
99 expect(
100 parseDelimitedPreview("Name, full;Role\nDoe, Jane;Engineer\nPrince;Artist", ",", {
101 inputComplete: false,
102 }).rows[0],
103 ).toEqual(["Name", " full;Role"]);
104 });
105 it("detects the delimiter immediately after a record-start closing quote", () => {
106 const sample = 'head;other,notes\r\n"first;value\r\nwith ""quotes""";last,more\r\n';
107 expect(parseDelimitedPreview(sample, ",")).toEqual({
108 rows: [
109 ["head", "other,notes"],
110 ['first;value\r\nwith "quotes"', "last,more"],
111 ],
112 truncated: false,
113 });
114
115 const splitAt = sample.indexOf(";last");
116 const detector = createCsvPreviewDetector();
117 expect(detector.push(sample.slice(0, splitAt))).toBeUndefined();
118 expect(detector.push(sample.slice(splitAt))).toBe(";");
119
120 const doubledQuoteSplit = createCsvPreviewDetector();
121 const quoteSplitAt = sample.indexOf('""quotes') + 1;
122 expect(doubledQuoteSplit.push(sample.slice(0, quoteSplitAt))).toBeUndefined();
123 expect(doubledQuoteSplit.push(sample.slice(quoteSplitAt))).toBe(";");
124
125 expect(parseDelimitedPreview('head,other;notes\nfoo;"bar";baz,qux\n', ",").rows).toEqual([
126 ["head", "other;notes"],
127 ['foo;"bar";baz', "qux"],
128 ]);
129 });
130 describe.each([",", "\t"] as const)("with delimiter %j", (delimiter) => {
131 it("preserves a final quoted empty record without requiring a line ending", () => {
132 for (const ending of ["", "\n", "\r\n"]) {
133 expect(parseDelimitedPreview(`name\r\nAlice\r\n""${ending}`, delimiter)).toEqual({
134 rows: [["name"], ["Alice"], [""]],
135 truncated: false,
136 });
137 }
138 expect(parseDelimitedPreview('""', delimiter)).toEqual({
139 rows: [[""]],
140 truncated: false,
141 });
142 });
143 it("does not invent records for empty input or a trailing line ending", () => {
144 for (const prefix of ["", "\ufeff"]) {
145 expect(parseDelimitedPreview(prefix, delimiter).rows).toEqual([]);
146 expect(parseDelimitedPreview(`${prefix}name\r\n`, delimiter).rows).toEqual([["name"]]);
147 expect(parseDelimitedPreview(`${prefix}""`, delimiter).rows).toEqual([[""]]);
148 }
149 });
150 it("keeps a quoted empty record at the row limit", () => {
151 const text = `${"name\n".repeat(99)}""`;
152 const preview = parseDelimitedPreview(text, delimiter);
153 expect(preview.rows).toHaveLength(100);
154 expect(preview.rows.at(-1)).toEqual([""]);
155 expect(preview.truncated).toBe(false);
156 expect(parseDelimitedPreview(`${text}\nextra`, delimiter).truncated).toBe(true);
157 });
158 });
159 it("bounds rows, columns and cell length and reports partial content", () => {
160 const table = parseDelimitedPreview(
161 Array.from({ length: 101 }, () =>
162 Array.from({ length: 31 }, () => "x".repeat(2001)).join(","),
163 ).join("\n"),
164 ",",
165 );
166 expect(table.truncated).toBe(true);
167 expect(table.rows).toHaveLength(100);
168 expect(table.rows[0]).toHaveLength(30);
169 expect(table.rows[0]?.[0]).toHaveLength(2000);
170 expect(parseDelimitedPreview('a,"unfinished', ",").truncated).toBe(true);
171 });
172 describe.each([",", "\t"] as const)("Unicode cells with delimiter %j", (delimiter) => {
173 it.each([false, true])("does not split surrogate pairs in quoted=%s cells", (quoted) => {
174 const prefix = "x".repeat(1999);
175 const value = `${prefix}😀tail`;
176 const input = `${quoted ? `"${value}"` : value}${delimiter}next\nlast`;
177 expect(parseDelimitedPreview(input, delimiter)).toEqual({
178 rows: [[prefix, "next"], ["last"]],
179 truncated: true,
180 });
181 });
182 it("keeps pairs that fit and truncates later characters", () => {
183 const value = `${"x".repeat(1998)}😀`;
184 expect(parseDelimitedPreview(value, delimiter)).toEqual({
185 rows: [[value]],
186 truncated: false,
187 });
188 expect(parseDelimitedPreview(`${value}tail`, delimiter)).toEqual({
189 rows: [[value]],
190 truncated: true,
191 });
192 });
193 it("keeps escaped quotes and BMP text at the same limit", () => {
194 const prefix = "x".repeat(1999);
195 expect(parseDelimitedPreview(`"${prefix}""tail"`, delimiter)).toEqual({
196 rows: [[`${prefix}"`]],
197 truncated: true,
198 });
199 expect(parseDelimitedPreview(`${prefix}éextra`, delimiter)).toEqual({
200 rows: [[`${prefix}é`]],
201 truncated: true,
202 });
203 });
204 });
205 it("reads worker pages beyond the old row, column and cell limits", () => {
206 const text = Array.from({ length: 128 }, (_, row) =>
207 Array.from({ length: 40 }, (_, column) => `${row}:${column}`).join(","),
208 ).join("\n");
209 const result = parseDelimitedPreview(text, ",", {
210 maxRows: 128,
211 maxColumns: 40,
212 maxCellLength: 4096,
213 });
214 expect(result.rows).toHaveLength(128);
215 expect(result.rows.at(-1)?.at(-1)).toBe("127:39");
216 expect(result.truncated).toBe(false);
217 expect(
218 parseDelimitedPreview(`"${"x".repeat(3000)}"`, ",", {
219 maxRows: 1,
220 maxColumns: 1,
221 maxCellLength: 4096,
222 }).rows[0]?.[0],
223 ).toHaveLength(3000);
224 });
225});