one CRUD, three callers — the browser and the agent stop writing iCalendar

the skill told an agent how to hand-write a .ics: escape the commas, fold at 75
octets, CRLF, DTSTAMP is required, and DTEND is the day after. all true, all
silent when wrong, and the browser had learned the same lesson separately in its
own copy of the code. this makes the sidecar the only thing that knows the
format, and gives everyone else fields.

WHAT WAS MISSING BEFORE THE SKILL COULD CHANGE. reading was already JSON, and
create-event landed this morning. this adds PATCH /_officer/item — change some
fields of an event or a card — and POST /_officer/contact. delete already worked.
with those the skill has no reason left to mention iCalendar, so it does not.

PATCH IS READ-PATCH-PUT, SERVER SIDE. it reads the stored text, replaces only the
lines it owns, and puts the whole thing back, so alarms, attendees, RRULEs and
every X- property a phone invented survive an edit made from a form that cannot
show them. that logic came out of the browser, where it had needed a duplicate of
the escaping and folding rules to live; the agent would have been a third copy in
bash. the web bundle now contains no iCalendar literals at all.

AND LIVE TESTING FOUND THE BUG THAT MATTERS. an event with a TZID is stored with
a VTIMEZONE block beside it, and that block has DTSTART lines of its own — the
rule for when summer time starts. taking the first DTSTART in the file rewrote
the TIMEZONE DEFINITION, left the event where it was, and answered ok. the
calendar showed the old time and the file was quietly corrupt. every write is now
confined to the first VEVENT or VCARD, and the file that caught it is a test.

three more traps handled rather than documented: a patch that reuses an all-day
event's stored DTEND must subtract the exclusive day first or the holiday drifts
every time the title is edited; moving a timed event must DROP a stale TZID
rather than preserve it, because a TZID and a Z together are a contradiction
clients resolve by moving the event; and a move bumps SEQUENCE, which is how a
phone tells an update from a duplicate.

contacts got the create form the calendar had, so both screens now do all four.
editing a card sends the other emails and phones back untouched — the form shows
the first of each, and sending only that would delete the rest.

47 tests across the writer and the patcher. verified live against a real event
carrying an alarm, an attendee, an RRULE and an X- property: all four intact
after a rename, a relocation and a move to a different day.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Officer-Session: 656f5c85-e49a-4f1f-b9f3-042a04b4d043
This commit is contained in:
2026-08-27 10:51:22 +00:00
co-authored by Claude Opus 5
parent 25c8502c4b
commit 43cb531dc2
10 changed files with 871 additions and 348 deletions
+28 -1
View File
@@ -1,4 +1,13 @@
import { buildEvent, parseContacts, parseEvents, type CalendarEvent, type Contact, type NewEvent } from './ical';
import {
buildContact,
buildEvent,
parseContacts,
parseEvents,
type CalendarEvent,
type Contact,
type NewContact,
type NewEvent,
} from './ical';
// The JSON door: what Officer's own web UI reads.
//
@@ -180,3 +189,21 @@ export async function createEvent(fetcher: Fetcher, collection: string, event: N
if (!res.ok) throw new Error(`radicale answered ${res.status}`);
return { href };
}
/** The same contract as `createEvent`, for a card. */
export async function createContact(
fetcher: Fetcher,
collection: string,
contact: NewContact,
): Promise<{ href: string }> {
const uid = crypto.randomUUID();
const href = `${collection.replace(/\/$/, '')}/${uid}.vcf`;
const res = await fetcher(href, {
method: 'PUT',
headers: { 'Content-Type': 'text/vcard; charset=utf-8', 'If-None-Match': '*' },
body: buildContact(uid, contact),
});
if (!res.ok) throw new Error(`radicale answered ${res.status}`);
return { href };
}
+45 -5
View File
@@ -211,7 +211,7 @@ export function parseContacts(vcf: string): Contact[] {
// ─── Writing ────────────────────────────────────────────────────────────────────────────────────────
const escapeText = (value: string) =>
export const escapeText = (value: string) =>
value
.replace(/\\/g, '\\\\')
.replace(/\r?\n/g, '\\n')
@@ -243,17 +243,17 @@ export function fold(line: string): string {
return out.join('\r\n');
}
const pad = (n: number) => String(n).padStart(2, '0');
export const pad = (n: number) => String(n).padStart(2, '0');
/** `20260827T140000Z`. Always UTC, so the file carries no timezone this codebase would have to resolve. */
const utcStamp = (date: Date) =>
export const utcStamp = (date: Date) =>
`${date.getUTCFullYear()}${pad(date.getUTCMonth() + 1)}${pad(date.getUTCDate())}T` +
`${pad(date.getUTCHours())}${pad(date.getUTCMinutes())}${pad(date.getUTCSeconds())}Z`;
/** `2026-08-27` → `20260827`. */
const dateStamp = (iso: string) => iso.slice(0, 10).replace(/-/g, '');
export const dateStamp = (iso: string) => iso.slice(0, 10).replace(/-/g, '');
const addDay = (iso: string) => {
export const addDay = (iso: string) => {
const d = new Date(`${iso.slice(0, 10)}T00:00:00Z`);
d.setUTCDate(d.getUTCDate() + 1);
return d.toISOString().slice(0, 10);
@@ -303,3 +303,43 @@ export function buildEvent(uid: string, event: NewEvent): string {
return lines.map(fold).join('\r\n') + '\r\n';
}
/** The inverse of `addDay`. Turns a file's EXCLUSIVE all-day DTEND back into the last day a person means. */
export const subDay = (iso: string) => {
const d = new Date(`${iso.slice(0, 10)}T00:00:00Z`);
d.setUTCDate(d.getUTCDate() - 1);
return d.toISOString().slice(0, 10);
};
export type NewContact = {
fullName: string;
emails?: string[];
phones?: string[];
org?: string;
title?: string;
};
/**
* A minimal vCard 3.0 — the version CardDAV clients, iOS included, actually write.
*
* `N` is REQUIRED in 3.0 and is `Family;Given;Middle;Prefix;Suffix`. Nobody supplies it, so it is split
* out of the full name: last word is the family name, everything before it is given. That is wrong for
* some names in the world and right for most, and `FN` — which is what a phone displays — is whatever
* was actually typed either way.
*/
export function buildContact(uid: string, contact: NewContact): string {
const [family, ...given] = contact.fullName.trim().split(/\s+/).reverse();
const lines = [
'BEGIN:VCARD',
'VERSION:3.0',
`UID:${uid}`,
`FN:${escapeText(contact.fullName)}`,
`N:${escapeText(family ?? '')};${escapeText(given.reverse().join(' '))};;;`,
];
for (const email of contact.emails ?? []) lines.push(`EMAIL;TYPE=INTERNET:${escapeText(email)}`);
for (const phone of contact.phones ?? []) lines.push(`TEL;TYPE=CELL:${escapeText(phone)}`);
if (contact.org) lines.push(`ORG:${escapeText(contact.org)}`);
if (contact.title) lines.push(`TITLE:${escapeText(contact.title)}`);
lines.push('END:VCARD');
return lines.map(fold).join('\r\n') + '\r\n';
}
+76 -2
View File
@@ -1,7 +1,8 @@
import type { SidecarCommand, SidecarEvent } from '@@/sidecar/protocol';
import { createSidecarConnector } from '@@/sidecar/connect';
import { startRadicale, davPaths } from './radicale';
import { listCollections, listEvents, listContacts, createEvent } from './collections';
import { listCollections, listEvents, listContacts, createEvent, createContact } from './collections';
import { patchFor, summarise } from './patch';
import { DATA_PATH } from '@@/data-path';
import { API_URL } from '@@/officer-url.mjs';
@@ -16,7 +17,10 @@ import { API_URL } from '@@/officer-url.mjs';
// Reached from the platform's TOP-LEVEL /dav mount, which authenticates a DAV
// app password over HTTP Basic. This is the door phones use.
// GET /_health is Radicale up, and does it answer.
// GET /_officer/* the JSON door for Officer's own web UI (see collections.ts).
// * /_officer/* the JSON door. Reads, and field-level writes: POST /_officer/event and
// /_officer/contact create, PATCH /_officer/item changes fields, DELETE removes.
// Built for the web UI; the agent skill speaks it too, which is why the writes
// take FIELDS rather than iCalendar text (see patch.ts).
//
// WHY TWO DOORS. A browser should not speak DAV — rendering a month view out of multistatus XML is a
// lot of machinery, and it would make the web UI as fragile as the protocol. The collections are on
@@ -203,6 +207,44 @@ const server = Bun.serve({
return Response.json({ href, data: await res.text() });
}
/*
Change some FIELDS of an item, rather than replacing its text.
This is the route anything sane should use. PUT is still here because the raw text is sometimes
genuinely what a caller has, but a caller that only wants to move an event or fix a phone number
should not have to learn iCalendar escaping to do it — and every caller that did learn it learned
it slightly differently. The read, the patch and the write happen here, in one round trip, over
the ORIGINAL text, so nothing the patcher does not recognise is disturbed.
*/
if (url.pathname === '/_officer/item' && req.method === 'PATCH') {
const body = (await req.json().catch(() => ({}))) as { href?: string; [field: string]: unknown };
const href = String(body.href ?? '');
if (!href.startsWith(`/dav/${userId}/`)) {
return Response.json({ error: 'href is required and must be your own' }, { status: 400 });
}
const read = await fetcher(href, { method: 'GET' });
if (!read.ok) return Response.json({ error: `radicale answered ${read.status}` }, { status: 502 });
let patched: string;
try {
const { href: _ignored, ...fields } = body;
patched = patchFor(href, fields, await read.text());
} catch (err) {
return Response.json({ error: String(err) }, { status: 400 });
}
const isCard = href.endsWith('.vcf');
const written = await fetcher(href, {
method: 'PUT',
headers: { 'Content-Type': isCard ? 'text/vcard; charset=utf-8' : 'text/calendar; charset=utf-8' },
body: patched,
});
if (!written.ok) return Response.json({ error: `radicale answered ${written.status}` }, { status: 502 });
// The item as it now reads, so a caller can confirm what it did without a second call.
return Response.json({ ok: true, item: summarise(href, patched) });
}
if (url.pathname === '/_officer/item' && (req.method === 'PUT' || req.method === 'DELETE')) {
const body = (await req.json().catch(() => ({}))) as { href?: string; data?: string };
const href = String(body.href ?? '');
@@ -270,6 +312,38 @@ const server = Bun.serve({
}
}
/* Same contract as the event route above, for an address book. */
if (url.pathname === '/_officer/contact' && req.method === 'POST') {
const body = (await req.json().catch(() => ({}))) as {
collection?: string;
fullName?: string;
emails?: string[];
phones?: string[];
org?: string;
title?: string;
};
const collection = String(body.collection ?? '');
if (!collection.startsWith(`/dav/${userId}/`)) {
return Response.json({ error: 'collection is required and must be your own' }, { status: 400 });
}
const fullName = (body.fullName ?? '').trim();
// FN is what a phone displays and vCard requires it. A card without one shows as a blank row.
if (!fullName) return Response.json({ error: 'fullName is required' }, { status: 400 });
try {
const created = await createContact(fetcher, collection, {
fullName,
emails: (body.emails ?? []).filter(Boolean),
phones: (body.phones ?? []).filter(Boolean),
org: (body.org ?? '').trim() || undefined,
title: (body.title ?? '').trim() || undefined,
});
return Response.json(created, { status: 201 });
} catch (err) {
return Response.json({ error: String(err) }, { status: 502 });
}
}
const path = url.searchParams.get('collection');
// Confine reads to this user's own tree. The header already scopes Radicale, but a path from a
// query string is attacker-shaped input and should not be handed on unchecked.
+240
View File
@@ -0,0 +1,240 @@
import { describe, expect, test } from 'bun:test';
import { patchContact, patchEvent, setProperty, setPropertyList } from './patch';
import { parseContacts, parseEvents } from './ical';
// What these protect: an edit must change what was asked and NOTHING else. Every failure mode here is
// silent — the write succeeds, the list still looks right, and something the UI cannot show is gone.
const EVENT = [
'BEGIN:VCALENDAR',
'VERSION:2.0',
'BEGIN:VEVENT',
'UID:abc',
'DTSTAMP:20260827T100000Z',
'DTSTART;TZID=Europe/Lisbon:20260828T130000',
'DTEND;TZID=Europe/Lisbon:20260828T140000',
'SUMMARY:Before',
'RRULE:FREQ=WEEKLY',
'ATTENDEE;CN=Someone:mailto:someone@example.com',
'X-APPLE-TRAVEL-ADVISORY-BEHAVIOR:AUTOMATIC',
'BEGIN:VALARM',
'ACTION:DISPLAY',
'TRIGGER:-PT15M',
'END:VALARM',
'END:VEVENT',
'END:VCALENDAR',
].join('\r\n');
const ALL_DAY = [
'BEGIN:VCALENDAR',
'VERSION:2.0',
'BEGIN:VEVENT',
'UID:def',
'DTSTAMP:20260827T100000Z',
'DTSTART;VALUE=DATE:20260829',
'DTEND;VALUE=DATE:20260830',
'SUMMARY:Holiday',
'END:VEVENT',
'END:VCALENDAR',
].join('\r\n');
const CARD = [
'BEGIN:VCARD',
'VERSION:3.0',
'UID:ghi',
'FN:Peter Griffin',
'N:Griffin;Peter;;;',
'EMAIL;TYPE=INTERNET:peter@quahog.example',
'EMAIL;TYPE=WORK:peter@brewery.example',
'TEL;TYPE=CELL:+351912345678',
'X-SOMETHING-ELSE:kept',
'END:VCARD',
].join('\r\n');
describe('setProperty', () => {
test('changes only the line it owns, and keeps what it does not understand', () => {
const out = setProperty(EVENT, 'SUMMARY', 'After');
expect(out).toContain('SUMMARY:After');
for (const kept of ['RRULE:FREQ=WEEKLY', 'ATTENDEE;CN=Someone', 'X-APPLE-TRAVEL', 'BEGIN:VALARM'])
expect(out).toContain(kept);
});
test('preserves parameters by default, and replaces them when told', () => {
expect(setProperty(EVENT, 'DTSTART', '20260901T090000')).toContain('DTSTART;TZID=Europe/Lisbon:20260901T090000');
expect(setProperty(EVENT, 'DTSTART', '20260901T090000Z', '')).toContain('DTSTART:20260901T090000Z');
});
test('appends after UID when absent, so it lands in the right component', () => {
const lines = setProperty(EVENT, 'LOCATION', 'Ramiro').split('\r\n');
expect(lines[lines.indexOf('UID:abc') + 1]).toBe('LOCATION:Ramiro');
});
test('null removes it', () => {
expect(setProperty(EVENT, 'RRULE', null)).not.toContain('RRULE');
});
// The regression that shipped once: replacing only the first line of a FOLDED value left the rest
// behind, and each edit inherited the tail of the last.
test('replaces the whole of a folded value', () => {
const folded = EVENT.replace('SUMMARY:Before', 'SUMMARY:Before and a great deal more text\r\n folded onto line two');
const out = setProperty(folded, 'SUMMARY', 'After');
expect(parseEvents(out)[0]!.summary).toBe('After');
expect(out).not.toContain('folded onto line two');
});
test('a long value is folded to 75 octets and reads back whole', () => {
const long = 'y'.repeat(300);
const out = setProperty(EVENT, 'SUMMARY', long);
expect(out.split('\r\n').every((l) => Buffer.byteLength(l, 'utf8') <= 75)).toBe(true);
expect(parseEvents(out)[0]!.summary).toBe(long);
});
test('repeated edits do not accumulate', () => {
let out = EVENT;
for (const v of ['one'.repeat(40), 'two'.repeat(40), 'three']) out = setProperty(out, 'SUMMARY', v);
expect(parseEvents(out)[0]!.summary).toBe('three');
});
});
describe('setPropertyList', () => {
test('replaces the whole list and carries parameters over by position', () => {
const out = setPropertyList(CARD, 'EMAIL', ['new@example.com'], ';TYPE=INTERNET');
expect(out).toContain('EMAIL;TYPE=INTERNET:new@example.com');
expect(out).not.toContain('brewery');
expect(parseContacts(out)[0]!.emails).toEqual(['new@example.com']);
});
test('extra values get the default parameters', () => {
const out = setPropertyList(CARD, 'TEL', ['+351911111111', '+351922222222'], ';TYPE=CELL');
expect(out).toContain('TEL;TYPE=CELL:+351911111111');
expect(out).toContain('TEL;TYPE=CELL:+351922222222');
});
test('an empty list removes them all, and leaves the rest of the card', () => {
const out = setPropertyList(CARD, 'EMAIL', [], ';TYPE=INTERNET');
expect(out).not.toContain('EMAIL');
expect(out).toContain('X-SOMETHING-ELSE:kept');
expect(out).toContain('TEL;TYPE=CELL:+351912345678');
});
});
describe('patchEvent', () => {
test('a text-only patch does not touch the times', () => {
const out = patchEvent(EVENT, { summary: 'After' });
expect(out).toContain('DTSTART;TZID=Europe/Lisbon:20260828T130000');
expect(out).not.toContain('SEQUENCE');
});
test('moving a timed event writes UTC and DROPS the stale TZID', () => {
const out = patchEvent(EVENT, { start: '2026-09-01T08:00:00Z', end: '2026-09-01T09:00:00Z' });
expect(out).toContain('DTSTART:20260901T080000Z');
expect(out).toContain('DTEND:20260901T090000Z');
expect(out).not.toContain('TZID');
});
test('moving bumps SEQUENCE, so a phone reads an update rather than a duplicate', () => {
const once = patchEvent(EVENT, { start: '2026-09-01T08:00:00Z' });
expect(once).toContain('SEQUENCE:1');
expect(patchEvent(once, { start: '2026-09-02T08:00:00Z' })).toContain('SEQUENCE:2');
});
test('changing only the end leaves the start exactly as it was', () => {
const out = patchEvent(ALL_DAY, { end: '2026-08-31' });
expect(out).toContain('DTSTART;VALUE=DATE:20260829');
expect(out).toContain('DTEND;VALUE=DATE:20260901'); // inclusive in, exclusive out
});
// The one that would silently move a holiday: the file's DTEND is exclusive, so editing anything else
// about the event must not re-add a day to it.
test('editing an all-day event does not drift its end', () => {
const out = patchEvent(patchEvent(ALL_DAY, { summary: 'A' }), { start: '2026-08-29' });
expect(out).toContain('DTEND;VALUE=DATE:20260830');
});
test('timed becomes all-day, both ends rewritten', () => {
const out = patchEvent(EVENT, { allDay: true, start: '2026-08-28' });
expect(out).toContain('DTSTART;VALUE=DATE:20260828');
expect(out).toContain('DTEND;VALUE=DATE:20260829');
expect(parseEvents(out)[0]!.allDay).toBe(true);
});
test('null removes a field, an empty string does not', () => {
const withPlace = patchEvent(EVENT, { location: 'Ramiro' });
expect(patchEvent(withPlace, { location: null })).not.toContain('LOCATION');
expect(patchEvent(withPlace, { location: '' })).toContain('LOCATION:');
});
test('separators are escaped and survive the round trip', () => {
const out = patchEvent(EVENT, { summary: 'a, b; c' });
expect(parseEvents(out)[0]!.summary).toBe('a, b; c');
});
});
describe('patchContact', () => {
test('renaming updates N as well as FN', () => {
const out = patchContact(CARD, { fullName: 'Lois Griffin' });
expect(out).toContain('FN:Lois Griffin');
expect(out).toContain('N:Griffin;Lois;;;');
});
test('a patch that names no list leaves both lists alone', () => {
const out = patchContact(CARD, { org: 'Pawtucket' });
expect(parseContacts(out)[0]!.emails).toEqual(['peter@quahog.example', 'peter@brewery.example']);
expect(out).toContain('ORG:Pawtucket');
});
test('everything unknown survives', () => {
expect(patchContact(CARD, { fullName: 'Peter L. Griffin' })).toContain('X-SOMETHING-ELSE:kept');
});
test('REV moves, because some clients break a tie with it', () => {
expect(patchContact(CARD, { title: 'Safety Inspector' })).toContain('REV:');
});
});
// The bug that live testing caught, and the reason `within` exists. Radicale stores a VTIMEZONE beside
// any event carrying a TZID, and that block has DTSTART lines of its own — the summer-time rule. Taking
// the first DTSTART in the file rewrote the timezone and left the event where it was.
const WITH_VTIMEZONE = [
'BEGIN:VCALENDAR',
'VERSION:2.0',
'BEGIN:VTIMEZONE',
'TZID:Europe/Lisbon',
'BEGIN:DAYLIGHT',
'DTSTART:20000326T010000',
'TZOFFSETFROM:+0000',
'RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=3',
'END:DAYLIGHT',
'END:VTIMEZONE',
'BEGIN:VEVENT',
'UID:jkl',
'DTSTAMP:20260827T100000Z',
'DTSTART;TZID=Europe/Lisbon:20260828T130000',
'DTEND;TZID=Europe/Lisbon:20260828T140000',
'SUMMARY:Probe',
'END:VEVENT',
'END:VCALENDAR',
].join('\r\n');
describe('a file with a VTIMEZONE', () => {
test('moving the event does not touch the timezone rule', () => {
const out = patchEvent(WITH_VTIMEZONE, { start: '2026-09-01T08:00:00Z', end: '2026-09-01T09:00:00Z' });
expect(out).toContain('DTSTART:20000326T010000'); // the summer-time rule, untouched
expect(out).toContain('DTSTART:20260901T080000Z'); // the event, moved
expect(out).not.toContain('DTSTART;TZID=Europe/Lisbon:20260828T130000');
expect(parseEvents(out)[0]!.start).toBe('2026-09-01T08:00:00Z');
});
test('the VTIMEZONE block survives intact', () => {
const out = patchEvent(WITH_VTIMEZONE, { summary: 'Renamed' });
for (const kept of ['BEGIN:VTIMEZONE', 'TZID:Europe/Lisbon', 'BEGIN:DAYLIGHT', 'TZOFFSETFROM:+0000'])
expect(out).toContain(kept);
expect(parseEvents(out)[0]!.summary).toBe('Renamed');
});
test('a summary is not appended into the wrong component', () => {
const out = patchEvent(WITH_VTIMEZONE, { location: 'Ramiro' });
const lines = out.split('\r\n');
expect(lines.indexOf('LOCATION:Ramiro')).toBeGreaterThan(lines.indexOf('BEGIN:VEVENT'));
});
});
+231
View File
@@ -0,0 +1,231 @@
import {
addDay,
dateStamp,
escapeText,
fold,
parseContacts,
parseEvents,
subDay,
utcStamp,
type CalendarEvent,
} from './ical';
/**
* Changing one field of an event or a card, without losing what this codebase does not understand.
*
* ── Read, patch, put — never rebuild ──
*
* A stored object holds far more than any of our screens show: alarms, attendees, recurrence rules,
* categories, every `X-` property the client that wrote it invented. Rebuilding it from the fields we
* parsed would silently drop all of that, and an edit that quietly deletes half an event is worse than
* no editing at all. So every function here takes the ORIGINAL text, replaces only the lines it owns,
* and hands the whole thing back.
*
* ── Why this is on the server ──
*
* It lived in the browser first, next to the form, and the folding rules had to be duplicated to get it
* there. Two copies of "escape a TEXT value and fold at 75 octets" is two places to be subtly wrong, and
* the agent skill needed the same logic a THIRD time in bash. One implementation, one round trip, three
* callers.
*/
/**
* Replace a property's line, or append it when the file has none. `null` removes it.
*
* A property is not always one line. RFC 5545 folds anything over 75 octets onto continuation lines
* starting with a space, so a long description is one property spread over several. Replacing only the
* first line leaves the rest behind, and they then fold onto whatever was written in its place — the new
* value silently grows the tail of the old one.
*
* `params` REPLACES the property's parameters when given, and preserves them when omitted. Both matter:
* `DTSTART;TZID=Europe/Lisbon` must not become a bare `DTSTART` when its value changes, and it must not
* KEEP that TZID when the new value is a UTC instant ending in Z — a timezone and a Z together are a
* contradiction some clients resolve by moving the event.
*/
export function setProperty(raw: string, prop: string, value: string | null, params?: string): string {
const lines = raw.split(/\r?\n/);
const at = lines.findIndex((l) => l === prop || l.startsWith(`${prop}:`) || l.startsWith(`${prop};`));
// Everything folded onto the property belongs to it.
let after = at + 1;
while (at !== -1 && after < lines.length && /^[ \t]/.test(lines[after]!)) after++;
if (value === null) return at === -1 ? raw : [...lines.slice(0, at), ...lines.slice(after)].join('\r\n');
if (at !== -1) {
const existing = /^[A-Z-]+(;[^:]*)?:/.exec(lines[at]!)?.[1] ?? '';
return [...lines.slice(0, at), fold(`${prop}${params ?? existing}:${value}`), ...lines.slice(after)].join('\r\n');
}
// Appended immediately after UID, so it lands in the right block of a file holding more than one.
const uidAt = lines.findIndex((l) => l.startsWith('UID:'));
const insertAt = uidAt === -1 ? Math.max(0, lines.length - 2) : uidAt + 1;
return [...lines.slice(0, insertAt), fold(`${prop}${params ?? ''}:${value}`), ...lines.slice(insertAt)].join('\r\n');
}
/**
* Replace every occurrence of a repeatable property — a card's EMAILs and TELs.
*
* Parameters are carried over BY POSITION: the first new phone keeps whatever the first old one had, so
* replacing a number does not quietly turn a mobile into an unlabelled one. Extra values get the default.
*/
export function setPropertyList(raw: string, prop: string, values: string[], fallbackParams: string): string {
const lines = raw.split(/\r?\n/);
const kept: string[] = [];
const oldParams: string[] = [];
let insertAt = -1;
for (let i = 0; i < lines.length; i++) {
const line = lines[i]!;
if (line.startsWith(`${prop}:`) || line.startsWith(`${prop};`)) {
if (insertAt === -1) insertAt = kept.length;
oldParams.push(/^[A-Z-]+(;[^:]*)?:/.exec(line)?.[1] ?? '');
while (i + 1 < lines.length && /^[ \t]/.test(lines[i + 1]!)) i++; // its continuation lines go too
continue;
}
kept.push(line);
}
if (insertAt === -1) {
const uidAt = kept.findIndex((l) => l.startsWith('UID:'));
insertAt = uidAt === -1 ? Math.max(0, kept.length - 1) : uidAt + 1;
}
const written = values.map((v, i) => fold(`${prop}${oldParams[i] ?? fallbackParams}:${escapeText(v)}`));
return [...kept.slice(0, insertAt), ...written, ...kept.slice(insertAt)].join('\r\n');
}
/**
* Confine a patch to one component's lines.
*
* FOUND THE HARD WAY, against a real file. A stored .ics is not a flat list of properties: an event with
* a TZID carries a VTIMEZONE block, and that block has DTSTART lines of its own — the rule for when
* summer time begins. A patch that takes the FIRST `DTSTART:` in the file rewrites the timezone
* definition, leaves the event's own start exactly where it was, and reports success. The calendar then
* shows the old time, and the file is quietly corrupt.
*
* So every write goes through here first. The properties it owns live inside `BEGIN:VEVENT` (or
* `BEGIN:VCARD`), and nothing outside is ever seen.
*
* THE FIRST component, when there are several. An .ics holding a recurring series plus overrides has one
* VEVENT per override, and the first is the master — which is what a list row shows and what an edit
* from it should change.
*/
function within(raw: string, component: 'VEVENT' | 'VCARD', edit: (body: string) => string): string {
const lines = raw.split(/\r?\n/);
const start = lines.indexOf(`BEGIN:${component}`);
const end = start === -1 ? -1 : lines.indexOf(`END:${component}`, start + 1);
// No wrapper — a bare fragment. Patch what there is rather than refusing.
if (start === -1 || end === -1) return edit(raw);
const body = edit(lines.slice(start + 1, end).join('\r\n'));
return [...lines.slice(0, start + 1), ...body.split(/\r?\n/), ...lines.slice(end)].join('\r\n');
}
/** A TEXT property: escaped, or removed when explicitly null. */
const text = (raw: string, prop: string, value: string | null | undefined) =>
value === undefined ? raw : setProperty(raw, prop, value === null ? null : escapeText(value));
export type EventPatch = {
summary?: string;
location?: string | null;
description?: string | null;
/** ISO instant, or `YYYY-MM-DD` for an all-day event. */
start?: string;
/** Same shape. For an all-day event this is the LAST day, inclusive — as a person means it. */
end?: string;
allDay?: boolean;
};
/**
* Apply a field patch to one .ics.
*
* TIMES ARE THE DELICATE PART. Three things have to move together and any one of them alone is a bug:
* the value's format (`20260901T090000Z` or `20260901`), the `VALUE=DATE` parameter that says which of
* those it is, and — for all-day — the exclusive DTEND. Changing a timed event to all-day rewrites both
* ends; changing only the end time leaves the start exactly as it was, TZID and all.
*/
export function patchEvent(raw: string, patch: EventPatch): string {
return within(raw, 'VEVENT', (body) => patchEventBody(body, raw, patch));
}
function patchEventBody(raw: string, whole: string, patch: EventPatch): string {
let out = text(raw, 'SUMMARY', patch.summary);
out = text(out, 'LOCATION', patch.location);
out = text(out, 'DESCRIPTION', patch.description);
const current: CalendarEvent | undefined = parseEvents(whole)[0];
const wasAllDay = Boolean(current?.allDay);
const allDay = patch.allDay ?? wasAllDay;
const movesTime = patch.start !== undefined || patch.end !== undefined || allDay !== wasAllDay;
if (!movesTime) return out;
const start = patch.start ?? current?.start;
if (!start) throw new Error('cannot move an event whose start could not be read');
// The file's all-day DTEND is EXCLUSIVE, so reusing it as-is would shift the event a day every time
// something else about it was edited. Normalise to the inclusive form the callers speak.
const existingEnd = current?.end && wasAllDay ? subDay(current.end) : current?.end;
const end = patch.end ?? existingEnd;
if (allDay) {
out = setProperty(out, 'DTSTART', dateStamp(start), ';VALUE=DATE');
out = setProperty(out, 'DTEND', dateStamp(addDay(end ?? start)), ';VALUE=DATE');
} else {
const startDate = new Date(start);
// An hour, matching what a new event with no end gets.
const endDate = end ? new Date(end) : new Date(startDate.getTime() + 60 * 60 * 1000);
out = setProperty(out, 'DTSTART', utcStamp(startDate), '');
out = setProperty(out, 'DTEND', utcStamp(endDate <= startDate ? startDate : endDate), '');
}
// Phones use SEQUENCE to tell an update from a duplicate, and LAST-MODIFIED is what a sync log shows.
const sequence = Number(/^SEQUENCE:(\d+)/m.exec(out)?.[1] ?? '0');
out = setProperty(out, 'SEQUENCE', String(sequence + 1), '');
return setProperty(out, 'LAST-MODIFIED', utcStamp(new Date()), '');
}
export type ContactPatch = {
fullName?: string;
emails?: string[];
phones?: string[];
org?: string | null;
title?: string | null;
};
/**
* Apply a field patch to one .vcf.
*
* `emails` and `phones` REPLACE the whole list, because that is the shape they are read in — what comes
* back from the listing is what goes into a patch. Sending one email to a card that had two removes the
* other, which is the only reading of "set the emails to this" that is not a guess.
*
* `N` follows `FN`, since a card whose display name and structured name disagree sorts under one and
* displays the other.
*/
export function patchContact(raw: string, patch: ContactPatch): string {
return within(raw, 'VCARD', (body) => patchContactBody(body, patch));
}
function patchContactBody(raw: string, patch: ContactPatch): string {
let out = raw;
if (patch.fullName !== undefined) {
const [family, ...given] = patch.fullName.trim().split(/\s+/).reverse();
out = setProperty(out, 'FN', escapeText(patch.fullName));
out = setProperty(out, 'N', `${escapeText(family ?? '')};${escapeText(given.reverse().join(' '))};;;`, '');
}
if (patch.emails !== undefined) out = setPropertyList(out, 'EMAIL', patch.emails, ';TYPE=INTERNET');
if (patch.phones !== undefined) out = setPropertyList(out, 'TEL', patch.phones, ';TYPE=CELL');
out = text(out, 'ORG', patch.org);
out = text(out, 'TITLE', patch.title);
// Not merely informational: some clients keep the copy with the later REV when two disagree.
return setProperty(out, 'REV', utcStamp(new Date()), '');
}
/** Which patcher a href needs. The extension is the only thing that distinguishes them. */
export const patchFor = (href: string, patch: EventPatch & ContactPatch, raw: string): string =>
href.endsWith('.vcf') ? patchContact(raw, patch) : patchEvent(raw, patch);
/** Present only so a caller can confirm what it read back. */
export const summarise = (href: string, raw: string) =>
href.endsWith('.vcf') ? parseContacts(raw)[0] : parseEvents(raw)[0];