Repository navigation
Expand file tree
/
Copy pathvcard.ts
More file actions
270 lines (253 loc) · 7.26 KB
/
Copy pathvcard.ts
File metadata and controls
270 lines (253 loc) · 7.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
/**
* Minimal vCard 3.0 helpers for the contact fields this server exposes.
*
* Parsing is line-based and tolerant: it unfolds continuation lines, ignores
* property groups and parameters, and leaves properties it does not model
* untouched. Updates are surgical — only the lines for the fields being
* changed are replaced, so data like PHOTO, ADR or BDAY written by other
* clients survives a round-trip through update-contact.
*/
export type ContactName = {
family?: string | undefined;
given?: string | undefined;
middle?: string | undefined;
prefix?: string | undefined;
suffix?: string | undefined;
};
export type ContactFields = {
uid?: string;
fn?: string;
name?: ContactName;
emails: string[];
phones: string[];
org?: string;
title?: string;
note?: string;
};
export type ContactUpdate = {
fn?: string | undefined;
name?: ContactName | undefined;
emails?: string[] | undefined;
phones?: string[] | undefined;
org?: string | undefined;
title?: string | undefined;
note?: string | undefined;
};
function escapeText(value: string): string {
return value
.replace(/\\/g, "\\\\")
.replace(/\r?\n/g, "\\n")
.replace(/;/g, "\\;")
.replace(/,/g, "\\,");
}
function unescapeText(value: string): string {
let out = "";
for (let i = 0; i < value.length; i++) {
const ch = value[i];
if (ch !== "\\") {
out += ch;
continue;
}
const next = value[i + 1];
if (next === "n" || next === "N") {
out += "\n";
i++;
} else if (next !== undefined) {
out += next;
i++;
}
}
return out;
}
/** Splits a property value on unescaped semicolons (vCard component lists). */
function splitComponents(value: string): string[] {
const parts: string[] = [];
let current = "";
for (let i = 0; i < value.length; i++) {
const ch = value[i];
if (ch === "\\" && i + 1 < value.length) {
current += ch + value[i + 1];
i++;
} else if (ch === ";") {
parts.push(current);
current = "";
} else {
current += ch;
}
}
parts.push(current);
return parts;
}
/** Unfolds RFC 6350 line continuations and returns the logical lines. */
function unfoldLines(data: string): string[] {
const lines: string[] = [];
for (const raw of data.split(/\r?\n/)) {
if ((raw.startsWith(" ") || raw.startsWith("\t")) && lines.length > 0) {
lines[lines.length - 1] += raw.slice(1);
} else if (raw.length > 0) {
lines.push(raw);
}
}
return lines;
}
/** Splits a logical line into its head (name + params) and raw value. */
function splitLine(line: string): { head: string; value: string } | null {
let inQuotes = false;
for (let i = 0; i < line.length; i++) {
const ch = line[i];
if (ch === '"') {
inQuotes = !inQuotes;
} else if (ch === ":" && !inQuotes) {
return { head: line.slice(0, i), value: line.slice(i + 1) };
}
}
return null;
}
/** Property name of a logical line, without group prefix or parameters. */
function propertyName(line: string): string | null {
const split = splitLine(line);
if (!split) return null;
const name = split.head.split(";")[0] ?? "";
const withoutGroup = name.includes(".")
? (name.split(".").pop() ?? "")
: name;
return withoutGroup.toUpperCase();
}
function parseName(value: string): ContactName {
const [family, given, middle, prefix, suffix] = splitComponents(value).map(
(c) => unescapeText(c),
);
return {
...(family && { family }),
...(given && { given }),
...(middle && { middle }),
...(prefix && { prefix }),
...(suffix && { suffix }),
};
}
export function parseVCard(data: string): ContactFields {
const fields: ContactFields = { emails: [], phones: [] };
for (const line of unfoldLines(data)) {
const split = splitLine(line);
const name = propertyName(line);
if (!split || !name) continue;
switch (name) {
case "UID":
fields.uid = unescapeText(split.value);
break;
case "FN":
fields.fn = unescapeText(split.value);
break;
case "N":
fields.name = parseName(split.value);
break;
case "EMAIL":
fields.emails.push(unescapeText(split.value));
break;
case "TEL":
fields.phones.push(unescapeText(split.value));
break;
case "ORG":
fields.org = splitComponents(split.value)
.map((c) => unescapeText(c))
.filter((c) => c.length > 0)
.join(", ");
break;
case "TITLE":
fields.title = unescapeText(split.value);
break;
case "NOTE":
fields.note = unescapeText(split.value);
break;
}
}
return fields;
}
/** Derives structured name parts from a formatted name (last token = family). */
function deriveName(fn: string): ContactName {
const tokens = fn.trim().split(/\s+/).filter(Boolean);
if (tokens.length === 0) return {};
if (tokens.length === 1) {
const given = tokens[0];
return given === undefined ? {} : { given };
}
const family = tokens[tokens.length - 1];
return {
...(family !== undefined && { family }),
given: tokens.slice(0, -1).join(" "),
};
}
function nameLine(name: ContactName): string {
const components = [
name.family ?? "",
name.given ?? "",
name.middle ?? "",
name.prefix ?? "",
name.suffix ?? "",
];
return `N:${components.map((c) => escapeText(c)).join(";")}`;
}
/**
* Renders the vCard lines for the given fields. Fields set to an empty
* string / empty array render no lines (used by updates to clear a field).
*/
function renderFieldLines(fields: ContactUpdate): string[] {
const lines: string[] = [];
if (fields.fn !== undefined && fields.fn !== "")
lines.push(`FN:${escapeText(fields.fn)}`);
if (fields.name !== undefined) lines.push(nameLine(fields.name));
for (const email of fields.emails ?? [])
lines.push(`EMAIL:${escapeText(email)}`);
for (const phone of fields.phones ?? [])
lines.push(`TEL:${escapeText(phone)}`);
if (fields.org !== undefined && fields.org !== "")
lines.push(`ORG:${escapeText(fields.org)}`);
if (fields.title !== undefined && fields.title !== "")
lines.push(`TITLE:${escapeText(fields.title)}`);
if (fields.note !== undefined && fields.note !== "")
lines.push(`NOTE:${escapeText(fields.note)}`);
return lines;
}
export function serializeVCard(
fields: { uid: string; fn: string } & Omit<ContactUpdate, "fn">,
): string {
const { uid, fn, name, ...rest } = fields;
const lines = [
"BEGIN:VCARD",
"VERSION:3.0",
`UID:${escapeText(uid)}`,
...renderFieldLines({ fn, name: name ?? deriveName(fn), ...rest }),
"END:VCARD",
];
return `${lines.join("\r\n")}\r\n`;
}
const PROPERTY_FOR_FIELD: Record<keyof ContactUpdate, string> = {
fn: "FN",
name: "N",
emails: "EMAIL",
phones: "TEL",
org: "ORG",
title: "TITLE",
note: "NOTE",
};
/**
* Applies a partial update to raw vCard data. Only lines for the provided
* fields are replaced; every other property is preserved verbatim.
*/
export function updateVCardData(data: string, updates: ContactUpdate): string {
const replaced = new Set(
(Object.keys(PROPERTY_FOR_FIELD) as Array<keyof ContactUpdate>)
.filter((field) => updates[field] !== undefined)
.map((field) => PROPERTY_FOR_FIELD[field]),
);
const kept = unfoldLines(data).filter((line) => {
const name = propertyName(line);
return name === null || !replaced.has(name);
});
const endIndex = kept.findIndex((line) => /^END:VCARD\s*$/i.test(line));
if (endIndex === -1) {
throw new Error("Invalid vCard: missing END:VCARD");
}
kept.splice(endIndex, 0, ...renderFieldLines(updates));
return `${kept.join("\r\n")}\r\n`;
}