Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
refactor(import/notion): reuse the shared CSV parser for the database header
Elian Dorandcf46dbece47
diff --git a/packages/commons/src/lib/csv.spec.ts b/packages/commons/src/lib/csv.spec.tsnew file mode 100644index 0000000000..579f186935--- /dev/null+++ b/packages/commons/src/lib/csv.spec.ts@@ -0,0 +1,26 @@+import { describe, expect, it } from "vitest";++import { parseCsv } from "./csv.js";++describe("parseCsv", () => {+ it("splits plain rows and fields", () => {+ expect(parseCsv("a,b,c\n1,2,3")).toEqual([["a", "b", "c"], ["1", "2", "3"]]);+ });++ it("handles quoted fields with embedded commas, newlines and doubled quotes", () => {+ expect(parseCsv(`"a,b","line1\nline2","he said ""hi"""`)).toEqual([["a,b", "line1\nline2", `he said "hi"`]]);+ });++ it("accepts CRLF, LF and CR record terminators", () => {+ expect(parseCsv("a,b\r\nc,d\ne,f\rg,h")).toEqual([["a", "b"], ["c", "d"], ["e", "f"], ["g", "h"]]);+ });++ it("strips a leading BOM, drops a single trailing terminator, but keeps a blank middle row", () => {+ const bom = String.fromCharCode(0xfeff);+ expect(parseCsv(`${bom}a,b\n\nc,d\n`)).toEqual([["a", "b"], [""], ["c", "d"]]);+ });++ it("returns no rows for empty input", () => {+ expect(parseCsv("")).toEqual([]);+ });+});diff --git a/packages/commons/src/lib/csv.ts b/packages/commons/src/lib/csv.tsnew file mode 100644index 0000000000..c515ff6b16--- /dev/null+++ b/packages/commons/src/lib/csv.ts@@ -0,0 +1,54 @@+/**+ * Minimal RFC 4180 CSV reader shared across imports (spreadsheets, Notion database columns).+ *+ * Tokenizes CSV text into a matrix of string fields: a quoted field may contain commas, newlines and+ * doubled `""` quotes; records may end in CRLF, LF or CR; a leading UTF-8 BOM is stripped. A single+ * trailing record terminator does not produce a spurious empty final row, but genuine blank lines in the+ * middle are preserved.+ */+export function parseCsv(csvText: string): string[][] {+ const text = stripBom(csvText);+ const rows: string[][] = [];+ let row: string[] = [];+ let field = "";+ let inQuotes = false;+ let i = 0;++ while (i < text.length) {+ const ch = text[i];++ if (inQuotes) {+ if (ch === "\"") {+ // A doubled quote inside a quoted field is a literal quote; a lone one closes it.+ if (text[i + 1] === "\"") { field += "\""; i += 2; continue; }+ inQuotes = false; i++; continue;+ }+ field += ch; i++; continue;+ }++ if (ch === "\"") { inQuotes = true; i++; continue; }+ if (ch === ",") { row.push(field); field = ""; i++; continue; }+ if (ch === "\n") { row.push(field); field = ""; rows.push(row); row = []; i++; continue; }+ if (ch === "\r") {+ row.push(field); field = ""; rows.push(row); row = [];+ i += text[i + 1] === "\n" ? 2 : 1; // swallow the LF of a CRLF pair+ continue;+ }++ field += ch; i++;+ }++ row.push(field);+ rows.push(row);++ // A trailing terminator leaves a final [""] record; drop it (but keep real empty fields).+ const last = rows[rows.length - 1];+ if (last.length === 1 && last[0] === "") rows.pop();++ return rows;+}++/** Strips a leading UTF-8 BOM (which our own spreadsheet exporter writes for Excel) if present. */+function stripBom(text: string): string {+ return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;+}diff --git a/packages/commons/src/lib/spreadsheet/parse_from_csv.ts b/packages/commons/src/lib/spreadsheet/parse_from_csv.tsindex b353634c5a..c31ff7653c 100644--- a/packages/commons/src/lib/spreadsheet/parse_from_csv.ts+++ b/packages/commons/src/lib/spreadsheet/parse_from_csv.ts@@ -13,6 +13,7 @@* no type for — stays a string.*/+import { parseCsv } from "../csv.js";import {CellValueType,type ICellData,@@ -28,7 +29,7 @@ const SHEET_ID = "sheet-0";/** Parses CSV text and produces a single-sheet UniversJS workbook. */export function parseCsvToWorkbook(csvText: string): PersistedData {- const rows = parseCsv(stripBom(csvText));+ const rows = parseCsv(csvText);const cellData = buildCellData(rows);const maxColumns = rows.reduce((max, row) => Math.max(max, row.length), 0);@@ -51,51 +52,6 @@ export function parseCsvToWorkbook(csvText: string): PersistedData {};}-/**- * Tokenizes CSV into a matrix of string fields. A single trailing record terminator does not- * produce a spurious empty final row, but genuine blank lines in the middle are preserved.- */-function parseCsv(text: string): string[][] {- const rows: string[][] = [];- let row: string[] = [];- let field = "";- let inQuotes = false;- let i = 0;-- while (i < text.length) {- const ch = text[i];-- if (inQuotes) {- if (ch === "\"") {- // A doubled quote inside a quoted field is a literal quote; a lone one closes it.- if (text[i + 1] === "\"") { field += "\""; i += 2; continue; }- inQuotes = false; i++; continue;- }- field += ch; i++; continue;- }-- if (ch === "\"") { inQuotes = true; i++; continue; }- if (ch === ",") { row.push(field); field = ""; i++; continue; }- if (ch === "\n") { row.push(field); field = ""; rows.push(row); row = []; i++; continue; }- if (ch === "\r") {- row.push(field); field = ""; rows.push(row); row = [];- i += text[i + 1] === "\n" ? 2 : 1; // swallow the LF of a CRLF pair- continue;- }-- field += ch; i++;- }-- row.push(field);- rows.push(row);-- // A trailing terminator leaves a final [""] record; drop it (but keep real empty fields).- const last = rows[rows.length - 1];- if (last.length === 1 && last[0] === "") rows.pop();-- return rows;-}-function buildCellData(rows: string[][]): Record<number, Record<number, ICellData>> {const cellData: Record<number, Record<number, ICellData>> = {};@@ -125,7 +81,3 @@ function toCell(value: string): ICellData | null {return { v: value, t: CellValueType.STRING };}--function stripBom(text: string): string {- return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;-}diff --git a/packages/trilium-core/src/services/import/notion/importer.ts b/packages/trilium-core/src/services/import/notion/importer.tsindex ba6c3ab603..f51bd941f6 100644--- a/packages/trilium-core/src/services/import/notion/importer.ts+++ b/packages/trilium-core/src/services/import/notion/importer.ts@@ -13,6 +13,7 @@*/import { dayjs, type LabelType, type Multiplicity } from "@triliumnext/commons";+import { parseCsv } from "@triliumnext/commons/src/lib/csv.js";import { t } from "i18next";import { HTMLElement, parse } from "node-html-parser";@@ -134,8 +135,8 @@ async function parseZip(fileBuffer: Uint8Array): Promise<{ pages: ParsedPage[];// A Notion database exports as a CSV: its path reconstructs the hierarchy (a database with no// own page), and its header row lists every column in the database's order.csvPaths.push(path);- const columns = parseCsvHeader(new TextDecoder().decode(await readContent()));- csvColumnsByFolder.set(ownedFolderKey(path), columns.map((column) => sanitizeAttributeName(column)));+ const [header = []] = parseCsv(new TextDecoder().decode(await readContent()));+ csvColumnsByFolder.set(ownedFolderKey(path), header.map((column) => sanitizeAttributeName(column)));} else {resources.set(normalizePath(path), await readContent());}@@ -147,42 +148,6 @@ async function parseZip(fileBuffer: Uint8Array): Promise<{ pages: ParsedPage[];return { pages, resources, csvPaths, csvColumnsByFolder };}-/**- * Parses the column names from a CSV export's header row, handling double-quoted fields (which may contain- * commas or escaped `""` quotes) and a leading UTF-8 BOM. Only the header row is needed for column order.- */-function parseCsvHeader(content: string): string[] {- const text = content.charCodeAt(0) === 0xfeff ? content.slice(1) : content;- const header = text.split(/\r?\n/, 1)[0] ?? "";- const columns: string[] = [];- let current = "";- let inQuotes = false;-- for (let i = 0; i < header.length; i++) {- const char = header[i];- if (inQuotes) {- if (char === '"' && header[i + 1] === '"') {- current += '"';- i++;- } else if (char === '"') {- inQuotes = false;- } else {- current += char;- }- } else if (char === '"') {- inQuotes = true;- } else if (char === ",") {- columns.push(current);- current = "";- } else {- current += char;- }- }- columns.push(current);-- return columns;-}-function parsePage(path: string, html: string): ParsedPage | null {const root = parse(html);