Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 62 additions & 11 deletions src/converters/vcf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,32 @@ export const properties = {
},
};

// Undo vCard text escapes: \, \; \\ and \n
const unescape = (value: string) =>
value.replace(/\\([,;\\nN])/g, (_, c) => (c === "n" || c === "N" ? "\n" : c));

// Split a structured value (N, ORG) on the ";" separators, not on escaped "\;" (but on "\\;")
const splitFields = (value: string) => value.split(/(?<=(?:^|[^\\])(?:\\\\)*);/);

// vCard 2.1 parameters: "ENCODING=QUOTED-PRINTABLE" or a bare "QUOTED-PRINTABLE"
const isQuotedPrintable = (params: string[]) =>
params.some((param) => /^(ENCODING=)?QUOTED-PRINTABLE$/i.test(param));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Quoted vCard parameter values are not normalized, so ENCODING="QUOTED-PRINTABLE" remains undecoded and quoted non-UTF-8 charsets corrupt decoded names. Normalize optional quotes before matching encoding and charset parameters.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At src/converters/vcf.ts, line 21:

<comment>Quoted vCard parameter values are not normalized, so `ENCODING="QUOTED-PRINTABLE"` remains undecoded and quoted non-UTF-8 charsets corrupt decoded names. Normalize optional quotes before matching encoding and charset parameters.</comment>

<file context>
@@ -9,6 +9,32 @@ export const properties = {
+
+// vCard 2.1 parameters: "ENCODING=QUOTED-PRINTABLE" or a bare "QUOTED-PRINTABLE"
+const isQuotedPrintable = (params: string[]) =>
+  params.some((param) => /^(ENCODING=)?QUOTED-PRINTABLE$/i.test(param));
+
+// vCard 2.1 exports (Android) write non-ASCII values as quoted-printable bytes in CHARSET
</file context>


// vCard 2.1 exports (Android) write non-ASCII values as quoted-printable bytes in CHARSET
const decodeQuotedPrintable = (value: string, params: string[]) => {
const bytes = Buffer.from(
value.replace(/=([0-9A-F]{2})/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16))),
"latin1",
);
const charset = (params.find((param) => /^CHARSET=/i.test(param))?.slice(8) ||
"utf-8") as ConstructorParameters<typeof TextDecoder>[0];
try {
return new TextDecoder(charset).decode(bytes);
} catch {
return bytes.toString("utf-8");
}
};

export function parseVCF(data: string): Record<string, string>[] {
const cards = data
.split(/BEGIN:VCARD/)
Expand All @@ -18,25 +44,50 @@ export function parseVCF(data: string): Record<string, string>[] {
return cards
.map((card) => {
if (!card) return {};
const lines = card.split("\n").filter((line) => line.trim());
const lines: string[] = [];
for (const raw of card.split("\n")) {
const line = raw.replace(/\r$/, "");
const prev = lines[lines.length - 1];
if (prev !== undefined && /^[ \t]/.test(line)) {
// a folded line continues the previous one after its leading space
lines[lines.length - 1] = prev + line.slice(1);
} else if (
prev?.endsWith("=") &&
isQuotedPrintable((prev.split(":")[0] || "").split(";"))
) {
// a quoted-printable value ending in "=" continues on the next line
lines[lines.length - 1] = prev.slice(0, -1) + line;
} else if (line.trim()) {
lines.push(line);
}
}
const contact: Record<string, string> = {};
const add = (field: string, value: string) => {
if (value) contact[field] = contact[field] ? `${contact[field]}; ${value}` : value;
};
for (const line of lines) {
const colonIndex = line.indexOf(":");
if (colonIndex === -1) continue;
const key = line.slice(0, colonIndex).trim();
// "item1.EMAIL;type=INTERNET" -> name EMAIL, params type=INTERNET
const [property = "", ...rawParams] = line.slice(0, colonIndex).trim().split(";");
const params = rawParams.map((param) => param.replace(/"/g, ""));
const key = property.replace(/^[^.]*\./, "").toUpperCase();
const value = line.slice(colonIndex + 1).trim();
// decode each field after splitting, so an encoded "=3B" is not a separator
const decode = (field = "") =>
unescape(isQuotedPrintable(params) ? decodeQuotedPrintable(field, params) : field);
if (key === "FN") {
contact["Full Name"] = value;
contact["Full Name"] = decode(value);
} else if (key === "N") {
const parts = value.split(";");
contact["Last Name"] = parts[0] || "";
contact["First Name"] = parts[1] || "";
} else if (key.startsWith("TEL")) {
contact["Phone"] = value;
} else if (key.startsWith("EMAIL")) {
contact["Email"] = value;
const parts = splitFields(value);
contact["Last Name"] = decode(parts[0]);
contact["First Name"] = decode(parts[1]);
} else if (key === "TEL") {
add("Phone", decode(value));
} else if (key === "EMAIL") {
add("Email", decode(value));
} else if (key === "ORG") {
contact["Organization"] = value.split(";")[0] || "";
contact["Organization"] = decode(splitFields(value)[0]);
}
}
return contact;
Expand Down
87 changes: 87 additions & 0 deletions tests/converters/vcf.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,93 @@ END:VCARD`;
]);
});

test("should keep every phone and email, including grouped ones", () => {
const vcfData = [
"BEGIN:VCARD",
"VERSION:3.0",
"FN:John Appleseed",
"ORG:Acme\\, Inc.;",
"item1.EMAIL;type=INTERNET;type=pref:john@example.com",
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
"item1.X-ABLabel:_$!<Other>!$_",
"TEL;type=CELL;type=pref:+1 555 123 4567",
"PHOTO;ENCODING=b;TYPE=JPEG:/9j/4AAQSkZJRg==",
"TEL;type=WORK:+1 555 987 6543",
"EMAIL;type=INTERNET;type=WORK:john@work.example",
"END:VCARD",
].join("\r\n");

expect(parseVCF(vcfData)).toEqual([
{
"Full Name": "John Appleseed",
Organization: "Acme, Inc.",
Email: "john@example.com; john@work.example",
Phone: "+1 555 123 4567; +1 555 987 6543",
},
]);
});

test("should decode quoted-printable names from vCard 2.1", () => {
const vcfData = [
"BEGIN:VCARD",
"VERSION:2.1",
"N;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:M=C3=BCller;J=C3=BCrgen;;;",
"FN;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:J=C3=BCrgen M=",
"=C3=BCller",
"END:VCARD",
].join("\r\n");

expect(parseVCF(vcfData)).toEqual([
{ "Last Name": "Müller", "First Name": "Jürgen", "Full Name": "Jürgen Müller" },
]);
});

test("should unfold long lines and keep escaped semicolons", () => {
const vcfData = [
"BEGIN:VCARD",
"VERSION:3.0",
"N:Doe\\;Smith;John;;;",
"FN:John Doe-Smith of the Very Long Name Department of the Company Papadimitrio",
" u Junior",
"ORG:R\\;D Labs;Research",
"END:VCARD",
].join("\r\n");

expect(parseVCF(vcfData)).toEqual([
{
"Last Name": "Doe;Smith",
"First Name": "John",
"Full Name":
"John Doe-Smith of the Very Long Name Department of the Company Papadimitriou Junior",
Organization: "R;D Labs",
},
]);
});

test("should split after an escaped backslash and decode fields after splitting", () => {
const vcfData = [
"BEGIN:VCARD",
"VERSION:2.1",
"N:Doe\\\\;John;;;",
'ORG;CHARSET=UTF-8;ENCODING="QUOTED-PRINTABLE":R=3BD Labs;Research',
"END:VCARD",
].join("\r\n");

expect(parseVCF(vcfData)).toEqual([
{ "Last Name": "Doe\\", "First Name": "John", Organization: "R;D Labs" },
]);
});

test("should decode quoted-printable values in their charset", () => {
const vcfData = [
"BEGIN:VCARD",
"VERSION:2.1",
"N;CHARSET=ISO-8859-1;QUOTED-PRINTABLE:M=FCller;J=FCrgen;;;",
"END:VCARD",
].join("\r\n");

expect(parseVCF(vcfData)).toEqual([{ "Last Name": "Müller", "First Name": "Jürgen" }]);
});

test("should handle CRLF line endings", () => {
const vcfData = "BEGIN:VCARD\r\nFN:John Doe\r\nTEL:123\r\nEND:VCARD\r\n";

Expand Down
Loading