calendaryjs-plugin-ics 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 calendaryjs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,104 @@
1
+ # calendaryjs-plugin-ics
2
+
3
+ ICS (RFC 5545) export for [calendaryjs](https://github.com/calendaryjs/calendaryjs). Turn generated calendar occurrences into a standard `.ics` `VCALENDAR` that Apple Calendar, Google Calendar, Outlook and anything else can subscribe to.
4
+
5
+ It is an **edge integration**: calendaryjs owns the calendar core; this package only serializes its plain output. It adds **zero runtime dependency** to the core and works on any plain object shaped like a `CalendarEvent`.
6
+
7
+ ## Features
8
+
9
+ - **๐Ÿ“ค One VEVENT per occurrence** โ€” events come in already expanded, so no `RRULE` is emitted. Lunar / hijri / formula dates and per-occurrence `exceptions` & `overrideDates` (already applied by the core) all export correctly.
10
+ - **โฐ Reminders โ†’ `VALARM`** โ€” each lead-time reminder becomes a relative-trigger alarm (`DISPLAY` or `EMAIL`).
11
+ - **๐Ÿ”ข Priority โ†’ `PRIORITY`** โ€” calendaryjs `priority` (CSS `z-index`: higher = on top) is inverted into ICS `PRIORITY` (1 = highest), with a pluggable mapper.
12
+ - **๐ŸŽจ Display fields** โ€” `DESCRIPTION`, `LOCATION`, `URL`, `CATEGORIES`, `STATUS`, plus RFC 7986 `COLOR` / `IMAGE`.
13
+ - **โœ… Spec-correct output** โ€” CRLF line endings, octet-aware line folding (75-octet, no multi-byte splits), RFC 5545 text escaping.
14
+ - **๐Ÿงช Deterministic** โ€” pass a fixed `dtstamp` for byte-stable, diff-friendly files.
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ pnpm add calendaryjs calendaryjs-plugin-ics
20
+ ```
21
+
22
+ ## Requirements
23
+
24
+ - `calendaryjs` >= 0.1.0
25
+
26
+ ## Quick Start
27
+
28
+ ```typescript
29
+ import { calendary } from "calendaryjs";
30
+ import { toICS } from "calendaryjs-plugin-ics";
31
+
32
+ const cal = calendary();
33
+ cal.addGroup({
34
+ id: "holidays",
35
+ name: "Holidays",
36
+ events: [
37
+ { type: "const", id: "newyear", month: 1, day: 1, title: "New Year" },
38
+ { type: "const", id: "christmas", month: 12, day: 25, title: "Christmas" },
39
+ ],
40
+ });
41
+
42
+ const events = cal.getEventsInRange("2025-01-01", "2025-12-31");
43
+ const ics = toICS(events, { calendarName: "Holidays" });
44
+
45
+ // โ†’ write `ics` to a .ics file, or serve it from an endpoint
46
+ ```
47
+
48
+ ## API
49
+
50
+ ### `toICS(events, options?) โ†’ string`
51
+
52
+ Serialize an array of occurrences into a full `VCALENDAR` document.
53
+
54
+ ```typescript
55
+ interface ICSOptions {
56
+ prodId?: string; // PRODID. Default "-//calendaryjs//calendaryjs-plugin-ics//EN"
57
+ calendarName?: string; // X-WR-CALNAME โ€” the calendar's display name
58
+ method?: string; // METHOD, e.g. "PUBLISH"
59
+ dtstamp?: Date; // DTSTAMP for every event. Default: now (pass a fixed Date for stable output)
60
+ priorityMap?: (priority: number) => number; // override priority โ†’ ICS PRIORITY (return 0 to omit)
61
+ }
62
+ ```
63
+
64
+ ### `eventToVEvent(event, options?) โ†’ string`
65
+
66
+ Serialize a single occurrence to one folded `VEVENT` block (no `VCALENDAR` wrapper).
67
+
68
+ Also exported: `veventLines` (unfolded lines), `defaultPriorityMap`, and the low-level `escapeText` / `foldLine` helpers.
69
+
70
+ ## Field mapping
71
+
72
+ | calendaryjs | ICS |
73
+ | ---------------------------------- | ----------------------------------------- |
74
+ | `date` + `startTime`/`endTime` | `DTSTART` / `DTEND` (floating local time) |
75
+ | `date` (all-day / no time) | `DTSTART;VALUE=DATE` + exclusive `DTEND` |
76
+ | `duration` (minutes) | `DURATION` (when `endTime` is absent) |
77
+ | `title` | `SUMMARY` |
78
+ | `description` / `location` / `url` | `DESCRIPTION` / `LOCATION` / `URL` |
79
+ | `categories` / `status` | `CATEGORIES` / `STATUS` |
80
+ | `priority` (z-index) | `PRIORITY` (inverted, 1 = highest) |
81
+ | `color` / `icon` | `COLOR` / `IMAGE` (RFC 7986) |
82
+ | `reminders[]` (minutes before) | `VALARM` with `TRIGGER:-PTnM` |
83
+ | `source` / `groupId` / id + `date` | a stable, unique `UID` |
84
+
85
+ ### Notes
86
+
87
+ - **Timezones.** Timed events export as **floating local time** (no `Z`, no `TZID`) โ€” the core stays timezone-neutral, so occurrences render in the viewer's local zone.
88
+ - **Reminder & duration units** are **minutes**.
89
+ - **`exceptions` / `overrideDates`** are resolved by the core before export (skipped occurrences are already gone, overrides already applied), so no `EXDATE` / `RECURRENCE-ID` is needed for the per-occurrence form.
90
+
91
+ ## Roadmap
92
+
93
+ - `RRULE` compaction for Gregorian-expressible recurrences (with `EXDATE` / `RECURRENCE-ID` for exceptions).
94
+ - ICS **import** (`.ics` โ†’ event configs).
95
+
96
+ ## Related Packages
97
+
98
+ - [calendaryjs](https://github.com/calendaryjs/calendaryjs/tree/main/packages/calendaryjs) โ€” core engine
99
+ - [calendaryjs-plugin-lunar](https://github.com/calendaryjs/calendaryjs/tree/main/packages/lunar) โ€” lunar calendar
100
+ - [calendaryjs-plugin-liturgical](https://github.com/calendaryjs/calendaryjs/tree/main/packages/liturgical) โ€” liturgical calendar
101
+
102
+ ## License
103
+
104
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,145 @@
1
+ 'use strict';
2
+
3
+ // src/escape.ts
4
+ var encoder = new TextEncoder();
5
+ function escapeText(value) {
6
+ return value.replace(/\\/g, "\\\\").replace(/;/g, "\\;").replace(/,/g, "\\,").replace(/\r\n|\r|\n/g, "\\n");
7
+ }
8
+ function foldLine(line) {
9
+ if (encoder.encode(line).length <= 75) return line;
10
+ let result = "";
11
+ let segment = "";
12
+ let segmentBytes = 0;
13
+ for (const char of line) {
14
+ const charBytes = encoder.encode(char).length;
15
+ const cap = result === "" ? 75 : 74;
16
+ if (segmentBytes + charBytes > cap) {
17
+ result += result === "" ? segment : `\r
18
+ ${segment}`;
19
+ segment = char;
20
+ segmentBytes = charBytes;
21
+ } else {
22
+ segment += char;
23
+ segmentBytes += charBytes;
24
+ }
25
+ }
26
+ result += result === "" ? segment : `\r
27
+ ${segment}`;
28
+ return result;
29
+ }
30
+
31
+ // src/format.ts
32
+ var pad2 = (value) => String(value).padStart(2, "0");
33
+ function formatDate(date) {
34
+ return date.replace(/-/g, "");
35
+ }
36
+ function formatTime(time) {
37
+ const [h = "0", m = "0", s = "0"] = time.split(":");
38
+ return `${pad2(h)}${pad2(m)}${pad2(s)}`;
39
+ }
40
+ function formatDateTime(date, time) {
41
+ return `${formatDate(date)}T${formatTime(time)}`;
42
+ }
43
+ function formatStamp(date) {
44
+ return `${date.getUTCFullYear()}${pad2(date.getUTCMonth() + 1)}${pad2(date.getUTCDate())}T${pad2(date.getUTCHours())}${pad2(date.getUTCMinutes())}${pad2(date.getUTCSeconds())}Z`;
45
+ }
46
+ function nextDateValue(date) {
47
+ const [y, m, d] = date.split("-").map(Number);
48
+ const next = new Date(Date.UTC(y, m - 1, d + 1));
49
+ return `${next.getUTCFullYear()}${pad2(next.getUTCMonth() + 1)}${pad2(next.getUTCDate())}`;
50
+ }
51
+ function formatDuration(minutes) {
52
+ if (minutes <= 0) return "PT0M";
53
+ const hours = Math.floor(minutes / 60);
54
+ const mins = minutes % 60;
55
+ return `PT${hours ? `${hours}H` : ""}${mins ? `${mins}M` : ""}`;
56
+ }
57
+
58
+ // src/vevent.ts
59
+ function defaultPriorityMap(priority) {
60
+ if (priority <= 0) return 0;
61
+ return Math.max(1, 9 - Math.min(priority, 8));
62
+ }
63
+ function valarmLines(reminder, fallback) {
64
+ const text = escapeText(reminder.message ?? fallback);
65
+ const lines = [
66
+ "BEGIN:VALARM",
67
+ `ACTION:${reminder.type === "email" ? "EMAIL" : "DISPLAY"}`,
68
+ `TRIGGER:-PT${Math.abs(reminder.trigger)}M`,
69
+ `DESCRIPTION:${text}`
70
+ ];
71
+ if (reminder.type === "email") lines.push(`SUMMARY:${text}`);
72
+ lines.push("END:VALARM");
73
+ return lines;
74
+ }
75
+ function veventLines(event, options = {}) {
76
+ const lines = ["BEGIN:VEVENT"];
77
+ const localPart = [event.groupId, event.sourceEventId ?? slug(event.title), event.date].filter(Boolean).join("-");
78
+ lines.push(`UID:${localPart}@${event.source ?? "calendaryjs"}`);
79
+ lines.push(`DTSTAMP:${formatStamp(options.dtstamp ?? /* @__PURE__ */ new Date())}`);
80
+ const allDay = event.allDay === true || !event.startTime;
81
+ if (allDay) {
82
+ lines.push(`DTSTART;VALUE=DATE:${formatDate(event.date)}`);
83
+ lines.push(`DTEND;VALUE=DATE:${nextDateValue(event.date)}`);
84
+ } else {
85
+ lines.push(`DTSTART:${formatDateTime(event.date, event.startTime)}`);
86
+ if (event.endTime) {
87
+ lines.push(`DTEND:${formatDateTime(event.date, event.endTime)}`);
88
+ } else if (event.duration) {
89
+ lines.push(`DURATION:${formatDuration(event.duration)}`);
90
+ }
91
+ }
92
+ lines.push(`SUMMARY:${escapeText(event.title)}`);
93
+ if (event.description) lines.push(`DESCRIPTION:${escapeText(event.description)}`);
94
+ if (event.location) lines.push(`LOCATION:${escapeText(event.location)}`);
95
+ if (event.url) lines.push(`URL:${event.url}`);
96
+ if (event.categories?.length) {
97
+ lines.push(`CATEGORIES:${event.categories.map(escapeText).join(",")}`);
98
+ }
99
+ if (event.status) lines.push(`STATUS:${event.status.toUpperCase()}`);
100
+ if (event.priority !== void 0) {
101
+ const map = options.priorityMap ?? defaultPriorityMap;
102
+ const icsPriority = map(event.priority);
103
+ if (icsPriority > 0) lines.push(`PRIORITY:${icsPriority}`);
104
+ }
105
+ if (event.color) lines.push(`COLOR:${event.color}`);
106
+ if (event.icon) lines.push(`IMAGE;VALUE=URI:${event.icon}`);
107
+ for (const reminder of event.reminders ?? []) {
108
+ lines.push(...valarmLines(reminder, event.title));
109
+ }
110
+ lines.push("END:VEVENT");
111
+ return lines;
112
+ }
113
+ function eventToVEvent(event, options = {}) {
114
+ return veventLines(event, options).map(foldLine).join("\r\n");
115
+ }
116
+ function slug(value) {
117
+ return value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "event";
118
+ }
119
+
120
+ // src/to-ics.ts
121
+ var DEFAULT_PRODID = "-//calendaryjs//calendaryjs-plugin-ics//EN";
122
+ function toICS(events, options = {}) {
123
+ const stamp = options.dtstamp ?? /* @__PURE__ */ new Date();
124
+ const lines = [
125
+ "BEGIN:VCALENDAR",
126
+ "VERSION:2.0",
127
+ `PRODID:${options.prodId ?? DEFAULT_PRODID}`,
128
+ "CALSCALE:GREGORIAN"
129
+ ];
130
+ if (options.method) lines.push(`METHOD:${options.method}`);
131
+ if (options.calendarName) lines.push(`X-WR-CALNAME:${escapeText(options.calendarName)}`);
132
+ const eventOptions = { ...options, dtstamp: stamp };
133
+ for (const event of events) {
134
+ lines.push(...veventLines(event, eventOptions));
135
+ }
136
+ lines.push("END:VCALENDAR");
137
+ return lines.map(foldLine).join("\r\n") + "\r\n";
138
+ }
139
+
140
+ exports.defaultPriorityMap = defaultPriorityMap;
141
+ exports.escapeText = escapeText;
142
+ exports.eventToVEvent = eventToVEvent;
143
+ exports.foldLine = foldLine;
144
+ exports.toICS = toICS;
145
+ exports.veventLines = veventLines;
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Plain, structural shape the ICS exporter consumes. A calendaryjs
3
+ * `CalendarEvent` satisfies it (see the structural assertion in
4
+ * `to-ics.test.ts`), but so does any plain object โ€” keeping this package an
5
+ * edge integration that never forces a calendaryjs runtime dependency.
6
+ *
7
+ * One `ICSEvent` = one already-expanded occurrence (a single calendar day).
8
+ * The core has already applied recurrence, `exceptions` and `overrideDates`,
9
+ * so the exporter emits one `VEVENT` per occurrence and needs no `RRULE`.
10
+ */
11
+ interface ICSEvent {
12
+ /** Occurrence date, `YYYY-MM-DD`. Required โ†’ `DTSTART`. */
13
+ date: string;
14
+ /** Required โ†’ `SUMMARY`. */
15
+ title: string;
16
+ /** All-day occurrence (no clock time) โ†’ `DTSTART;VALUE=DATE`. */
17
+ allDay?: boolean;
18
+ /** Start clock time, `HH:mm` or `HH:mm:ss` (floating/local). */
19
+ startTime?: string;
20
+ /** End clock time, `HH:mm` or `HH:mm:ss`. */
21
+ endTime?: string;
22
+ /** Duration in **minutes** โ†’ `DURATION` (used when `endTime` is absent). */
23
+ duration?: number;
24
+ /** โ†’ `DESCRIPTION`. */
25
+ description?: string;
26
+ /** โ†’ `LOCATION`. */
27
+ location?: string;
28
+ /** โ†’ `URL`. */
29
+ url?: string;
30
+ /** Origin feed/plugin โ€” used as the `UID` domain so re-imports dedupe. */
31
+ source?: string;
32
+ /** โ†’ `CATEGORIES`. */
33
+ categories?: string[];
34
+ /**
35
+ * calendaryjs display precedence (CSS `z-index`: higher = on top, default 0).
36
+ * Inverted into ICS `PRIORITY` (1 = highest, 9 = lowest, 0 = undefined) by
37
+ * {@link ICSOptions.priorityMap}.
38
+ */
39
+ priority?: number;
40
+ /** โ†’ `STATUS` (`CONFIRMED` / `TENTATIVE` / `CANCELLED`). */
41
+ status?: "confirmed" | "tentative" | "cancelled";
42
+ /** CSS3 colour name โ†’ `COLOR` (RFC 7986). */
43
+ color?: string;
44
+ /** Image URI โ†’ `IMAGE` (RFC 7986). */
45
+ icon?: string;
46
+ /** Lead-time reminders โ†’ one `VALARM` each. */
47
+ reminders?: ICSReminder[];
48
+ /** Originating config id โ€” part of a stable `UID`. */
49
+ sourceEventId?: string;
50
+ /** Group id โ€” part of a stable `UID`. */
51
+ groupId?: string;
52
+ }
53
+ /** A single reminder โ†’ one `VALARM` with a relative `TRIGGER`. */
54
+ interface ICSReminder {
55
+ /** `notification` โ†’ `ACTION:DISPLAY`; `email` โ†’ `ACTION:EMAIL`. */
56
+ type?: "notification" | "email";
57
+ /** Lead time in **minutes before** the occurrence โ†’ `TRIGGER:-PTnM`. */
58
+ trigger: number;
59
+ /** Reminder text โ†’ `DESCRIPTION` (falls back to the event title). */
60
+ message?: string;
61
+ }
62
+ /** Options for {@link toICS} and {@link eventToVEvent}. */
63
+ interface ICSOptions {
64
+ /** `PRODID`. Default `-//calendaryjs//calendaryjs-plugin-ics//EN`. */
65
+ prodId?: string;
66
+ /** `X-WR-CALNAME` โ€” the calendar's display name. */
67
+ calendarName?: string;
68
+ /** `METHOD` (e.g. `PUBLISH`). Omitted by default. */
69
+ method?: string;
70
+ /**
71
+ * `DTSTAMP` for every event. Defaults to the current time; pass a fixed
72
+ * `Date` for deterministic, diff-friendly output.
73
+ */
74
+ dtstamp?: Date;
75
+ /**
76
+ * Map a calendaryjs `priority` (z-index) to an ICS `PRIORITY` (1 = highest,
77
+ * 9 = lowest). Return `0` to omit. Default: importance inverts to rank, so a
78
+ * higher calendaryjs priority becomes a lower (more urgent) ICS number.
79
+ */
80
+ priorityMap?: (priority: number) => number;
81
+ }
82
+
83
+ /**
84
+ * Serialize an array of already-expanded occurrences into a single RFC 5545
85
+ * `VCALENDAR` document (CRLF line endings, octet-folded). One `VEVENT` is
86
+ * emitted per occurrence โ€” no `RRULE` โ€” so non-Gregorian recurrences (lunar,
87
+ * hijri) and per-occurrence `exceptions`/`overrideDates` (already applied by
88
+ * the core) export correctly.
89
+ *
90
+ * @example
91
+ * ```typescript
92
+ * import { calendary } from "calendaryjs";
93
+ * import { toICS } from "calendaryjs-plugin-ics";
94
+ *
95
+ * const cal = calendary();
96
+ * // ... add events ...
97
+ * const events = cal.getEventsInRange("2025-01-01", "2025-12-31");
98
+ * const ics = toICS(events, { calendarName: "Family" });
99
+ * ```
100
+ */
101
+ declare function toICS(events: ICSEvent[], options?: ICSOptions): string;
102
+
103
+ /**
104
+ * Default mapping from a calendaryjs `priority` (z-index: higher = more
105
+ * important, unbounded, default 0) to an ICS `PRIORITY` (1 = highest, 9 =
106
+ * lowest, 0 = undefined). Importance inverts to rank and is clamped to 1โ€“9, so
107
+ * `0` stays undefined, `1` โ†’ `9` (low) and `โ‰ฅ8` โ†’ `1` (top).
108
+ */
109
+ declare function defaultPriorityMap(priority: number): number;
110
+ /**
111
+ * Serialize one occurrence into the raw (unfolded) lines of a `VEVENT`
112
+ * component. Used by {@link toICS}; folding is applied when the calendar is
113
+ * assembled. Returns lines so the caller controls folding/joining.
114
+ */
115
+ declare function veventLines(event: ICSEvent, options?: ICSOptions): string[];
116
+ /**
117
+ * Serialize one occurrence to a folded `VEVENT` block (CRLF-joined). For a
118
+ * full calendar use {@link toICS}.
119
+ */
120
+ declare function eventToVEvent(event: ICSEvent, options?: ICSOptions): string;
121
+
122
+ /**
123
+ * RFC 5545 text escaping and content-line folding.
124
+ */
125
+ /**
126
+ * Escape a TEXT value per RFC 5545 ยง3.3.11: backslash, semicolon, comma and
127
+ * newlines. The backslash must be replaced first so the escapes it introduces
128
+ * are not double-escaped.
129
+ */
130
+ declare function escapeText(value: string): string;
131
+ /**
132
+ * Fold a single content line to โ‰ค75 octets per RFC 5545 ยง3.1, breaking on
133
+ * octet (UTF-8 byte) boundaries โ€” never inside a multi-byte character โ€” and
134
+ * continuing with CRLF + a single leading space. Continuation lines reserve
135
+ * one octet for that space, so their content cap is 74. Short lines are
136
+ * returned unchanged.
137
+ */
138
+ declare function foldLine(line: string): string;
139
+
140
+ export { type ICSEvent, type ICSOptions, type ICSReminder, defaultPriorityMap, escapeText, eventToVEvent, foldLine, toICS, veventLines };
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Plain, structural shape the ICS exporter consumes. A calendaryjs
3
+ * `CalendarEvent` satisfies it (see the structural assertion in
4
+ * `to-ics.test.ts`), but so does any plain object โ€” keeping this package an
5
+ * edge integration that never forces a calendaryjs runtime dependency.
6
+ *
7
+ * One `ICSEvent` = one already-expanded occurrence (a single calendar day).
8
+ * The core has already applied recurrence, `exceptions` and `overrideDates`,
9
+ * so the exporter emits one `VEVENT` per occurrence and needs no `RRULE`.
10
+ */
11
+ interface ICSEvent {
12
+ /** Occurrence date, `YYYY-MM-DD`. Required โ†’ `DTSTART`. */
13
+ date: string;
14
+ /** Required โ†’ `SUMMARY`. */
15
+ title: string;
16
+ /** All-day occurrence (no clock time) โ†’ `DTSTART;VALUE=DATE`. */
17
+ allDay?: boolean;
18
+ /** Start clock time, `HH:mm` or `HH:mm:ss` (floating/local). */
19
+ startTime?: string;
20
+ /** End clock time, `HH:mm` or `HH:mm:ss`. */
21
+ endTime?: string;
22
+ /** Duration in **minutes** โ†’ `DURATION` (used when `endTime` is absent). */
23
+ duration?: number;
24
+ /** โ†’ `DESCRIPTION`. */
25
+ description?: string;
26
+ /** โ†’ `LOCATION`. */
27
+ location?: string;
28
+ /** โ†’ `URL`. */
29
+ url?: string;
30
+ /** Origin feed/plugin โ€” used as the `UID` domain so re-imports dedupe. */
31
+ source?: string;
32
+ /** โ†’ `CATEGORIES`. */
33
+ categories?: string[];
34
+ /**
35
+ * calendaryjs display precedence (CSS `z-index`: higher = on top, default 0).
36
+ * Inverted into ICS `PRIORITY` (1 = highest, 9 = lowest, 0 = undefined) by
37
+ * {@link ICSOptions.priorityMap}.
38
+ */
39
+ priority?: number;
40
+ /** โ†’ `STATUS` (`CONFIRMED` / `TENTATIVE` / `CANCELLED`). */
41
+ status?: "confirmed" | "tentative" | "cancelled";
42
+ /** CSS3 colour name โ†’ `COLOR` (RFC 7986). */
43
+ color?: string;
44
+ /** Image URI โ†’ `IMAGE` (RFC 7986). */
45
+ icon?: string;
46
+ /** Lead-time reminders โ†’ one `VALARM` each. */
47
+ reminders?: ICSReminder[];
48
+ /** Originating config id โ€” part of a stable `UID`. */
49
+ sourceEventId?: string;
50
+ /** Group id โ€” part of a stable `UID`. */
51
+ groupId?: string;
52
+ }
53
+ /** A single reminder โ†’ one `VALARM` with a relative `TRIGGER`. */
54
+ interface ICSReminder {
55
+ /** `notification` โ†’ `ACTION:DISPLAY`; `email` โ†’ `ACTION:EMAIL`. */
56
+ type?: "notification" | "email";
57
+ /** Lead time in **minutes before** the occurrence โ†’ `TRIGGER:-PTnM`. */
58
+ trigger: number;
59
+ /** Reminder text โ†’ `DESCRIPTION` (falls back to the event title). */
60
+ message?: string;
61
+ }
62
+ /** Options for {@link toICS} and {@link eventToVEvent}. */
63
+ interface ICSOptions {
64
+ /** `PRODID`. Default `-//calendaryjs//calendaryjs-plugin-ics//EN`. */
65
+ prodId?: string;
66
+ /** `X-WR-CALNAME` โ€” the calendar's display name. */
67
+ calendarName?: string;
68
+ /** `METHOD` (e.g. `PUBLISH`). Omitted by default. */
69
+ method?: string;
70
+ /**
71
+ * `DTSTAMP` for every event. Defaults to the current time; pass a fixed
72
+ * `Date` for deterministic, diff-friendly output.
73
+ */
74
+ dtstamp?: Date;
75
+ /**
76
+ * Map a calendaryjs `priority` (z-index) to an ICS `PRIORITY` (1 = highest,
77
+ * 9 = lowest). Return `0` to omit. Default: importance inverts to rank, so a
78
+ * higher calendaryjs priority becomes a lower (more urgent) ICS number.
79
+ */
80
+ priorityMap?: (priority: number) => number;
81
+ }
82
+
83
+ /**
84
+ * Serialize an array of already-expanded occurrences into a single RFC 5545
85
+ * `VCALENDAR` document (CRLF line endings, octet-folded). One `VEVENT` is
86
+ * emitted per occurrence โ€” no `RRULE` โ€” so non-Gregorian recurrences (lunar,
87
+ * hijri) and per-occurrence `exceptions`/`overrideDates` (already applied by
88
+ * the core) export correctly.
89
+ *
90
+ * @example
91
+ * ```typescript
92
+ * import { calendary } from "calendaryjs";
93
+ * import { toICS } from "calendaryjs-plugin-ics";
94
+ *
95
+ * const cal = calendary();
96
+ * // ... add events ...
97
+ * const events = cal.getEventsInRange("2025-01-01", "2025-12-31");
98
+ * const ics = toICS(events, { calendarName: "Family" });
99
+ * ```
100
+ */
101
+ declare function toICS(events: ICSEvent[], options?: ICSOptions): string;
102
+
103
+ /**
104
+ * Default mapping from a calendaryjs `priority` (z-index: higher = more
105
+ * important, unbounded, default 0) to an ICS `PRIORITY` (1 = highest, 9 =
106
+ * lowest, 0 = undefined). Importance inverts to rank and is clamped to 1โ€“9, so
107
+ * `0` stays undefined, `1` โ†’ `9` (low) and `โ‰ฅ8` โ†’ `1` (top).
108
+ */
109
+ declare function defaultPriorityMap(priority: number): number;
110
+ /**
111
+ * Serialize one occurrence into the raw (unfolded) lines of a `VEVENT`
112
+ * component. Used by {@link toICS}; folding is applied when the calendar is
113
+ * assembled. Returns lines so the caller controls folding/joining.
114
+ */
115
+ declare function veventLines(event: ICSEvent, options?: ICSOptions): string[];
116
+ /**
117
+ * Serialize one occurrence to a folded `VEVENT` block (CRLF-joined). For a
118
+ * full calendar use {@link toICS}.
119
+ */
120
+ declare function eventToVEvent(event: ICSEvent, options?: ICSOptions): string;
121
+
122
+ /**
123
+ * RFC 5545 text escaping and content-line folding.
124
+ */
125
+ /**
126
+ * Escape a TEXT value per RFC 5545 ยง3.3.11: backslash, semicolon, comma and
127
+ * newlines. The backslash must be replaced first so the escapes it introduces
128
+ * are not double-escaped.
129
+ */
130
+ declare function escapeText(value: string): string;
131
+ /**
132
+ * Fold a single content line to โ‰ค75 octets per RFC 5545 ยง3.1, breaking on
133
+ * octet (UTF-8 byte) boundaries โ€” never inside a multi-byte character โ€” and
134
+ * continuing with CRLF + a single leading space. Continuation lines reserve
135
+ * one octet for that space, so their content cap is 74. Short lines are
136
+ * returned unchanged.
137
+ */
138
+ declare function foldLine(line: string): string;
139
+
140
+ export { type ICSEvent, type ICSOptions, type ICSReminder, defaultPriorityMap, escapeText, eventToVEvent, foldLine, toICS, veventLines };
package/dist/index.js ADDED
@@ -0,0 +1,138 @@
1
+ // src/escape.ts
2
+ var encoder = new TextEncoder();
3
+ function escapeText(value) {
4
+ return value.replace(/\\/g, "\\\\").replace(/;/g, "\\;").replace(/,/g, "\\,").replace(/\r\n|\r|\n/g, "\\n");
5
+ }
6
+ function foldLine(line) {
7
+ if (encoder.encode(line).length <= 75) return line;
8
+ let result = "";
9
+ let segment = "";
10
+ let segmentBytes = 0;
11
+ for (const char of line) {
12
+ const charBytes = encoder.encode(char).length;
13
+ const cap = result === "" ? 75 : 74;
14
+ if (segmentBytes + charBytes > cap) {
15
+ result += result === "" ? segment : `\r
16
+ ${segment}`;
17
+ segment = char;
18
+ segmentBytes = charBytes;
19
+ } else {
20
+ segment += char;
21
+ segmentBytes += charBytes;
22
+ }
23
+ }
24
+ result += result === "" ? segment : `\r
25
+ ${segment}`;
26
+ return result;
27
+ }
28
+
29
+ // src/format.ts
30
+ var pad2 = (value) => String(value).padStart(2, "0");
31
+ function formatDate(date) {
32
+ return date.replace(/-/g, "");
33
+ }
34
+ function formatTime(time) {
35
+ const [h = "0", m = "0", s = "0"] = time.split(":");
36
+ return `${pad2(h)}${pad2(m)}${pad2(s)}`;
37
+ }
38
+ function formatDateTime(date, time) {
39
+ return `${formatDate(date)}T${formatTime(time)}`;
40
+ }
41
+ function formatStamp(date) {
42
+ return `${date.getUTCFullYear()}${pad2(date.getUTCMonth() + 1)}${pad2(date.getUTCDate())}T${pad2(date.getUTCHours())}${pad2(date.getUTCMinutes())}${pad2(date.getUTCSeconds())}Z`;
43
+ }
44
+ function nextDateValue(date) {
45
+ const [y, m, d] = date.split("-").map(Number);
46
+ const next = new Date(Date.UTC(y, m - 1, d + 1));
47
+ return `${next.getUTCFullYear()}${pad2(next.getUTCMonth() + 1)}${pad2(next.getUTCDate())}`;
48
+ }
49
+ function formatDuration(minutes) {
50
+ if (minutes <= 0) return "PT0M";
51
+ const hours = Math.floor(minutes / 60);
52
+ const mins = minutes % 60;
53
+ return `PT${hours ? `${hours}H` : ""}${mins ? `${mins}M` : ""}`;
54
+ }
55
+
56
+ // src/vevent.ts
57
+ function defaultPriorityMap(priority) {
58
+ if (priority <= 0) return 0;
59
+ return Math.max(1, 9 - Math.min(priority, 8));
60
+ }
61
+ function valarmLines(reminder, fallback) {
62
+ const text = escapeText(reminder.message ?? fallback);
63
+ const lines = [
64
+ "BEGIN:VALARM",
65
+ `ACTION:${reminder.type === "email" ? "EMAIL" : "DISPLAY"}`,
66
+ `TRIGGER:-PT${Math.abs(reminder.trigger)}M`,
67
+ `DESCRIPTION:${text}`
68
+ ];
69
+ if (reminder.type === "email") lines.push(`SUMMARY:${text}`);
70
+ lines.push("END:VALARM");
71
+ return lines;
72
+ }
73
+ function veventLines(event, options = {}) {
74
+ const lines = ["BEGIN:VEVENT"];
75
+ const localPart = [event.groupId, event.sourceEventId ?? slug(event.title), event.date].filter(Boolean).join("-");
76
+ lines.push(`UID:${localPart}@${event.source ?? "calendaryjs"}`);
77
+ lines.push(`DTSTAMP:${formatStamp(options.dtstamp ?? /* @__PURE__ */ new Date())}`);
78
+ const allDay = event.allDay === true || !event.startTime;
79
+ if (allDay) {
80
+ lines.push(`DTSTART;VALUE=DATE:${formatDate(event.date)}`);
81
+ lines.push(`DTEND;VALUE=DATE:${nextDateValue(event.date)}`);
82
+ } else {
83
+ lines.push(`DTSTART:${formatDateTime(event.date, event.startTime)}`);
84
+ if (event.endTime) {
85
+ lines.push(`DTEND:${formatDateTime(event.date, event.endTime)}`);
86
+ } else if (event.duration) {
87
+ lines.push(`DURATION:${formatDuration(event.duration)}`);
88
+ }
89
+ }
90
+ lines.push(`SUMMARY:${escapeText(event.title)}`);
91
+ if (event.description) lines.push(`DESCRIPTION:${escapeText(event.description)}`);
92
+ if (event.location) lines.push(`LOCATION:${escapeText(event.location)}`);
93
+ if (event.url) lines.push(`URL:${event.url}`);
94
+ if (event.categories?.length) {
95
+ lines.push(`CATEGORIES:${event.categories.map(escapeText).join(",")}`);
96
+ }
97
+ if (event.status) lines.push(`STATUS:${event.status.toUpperCase()}`);
98
+ if (event.priority !== void 0) {
99
+ const map = options.priorityMap ?? defaultPriorityMap;
100
+ const icsPriority = map(event.priority);
101
+ if (icsPriority > 0) lines.push(`PRIORITY:${icsPriority}`);
102
+ }
103
+ if (event.color) lines.push(`COLOR:${event.color}`);
104
+ if (event.icon) lines.push(`IMAGE;VALUE=URI:${event.icon}`);
105
+ for (const reminder of event.reminders ?? []) {
106
+ lines.push(...valarmLines(reminder, event.title));
107
+ }
108
+ lines.push("END:VEVENT");
109
+ return lines;
110
+ }
111
+ function eventToVEvent(event, options = {}) {
112
+ return veventLines(event, options).map(foldLine).join("\r\n");
113
+ }
114
+ function slug(value) {
115
+ return value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "event";
116
+ }
117
+
118
+ // src/to-ics.ts
119
+ var DEFAULT_PRODID = "-//calendaryjs//calendaryjs-plugin-ics//EN";
120
+ function toICS(events, options = {}) {
121
+ const stamp = options.dtstamp ?? /* @__PURE__ */ new Date();
122
+ const lines = [
123
+ "BEGIN:VCALENDAR",
124
+ "VERSION:2.0",
125
+ `PRODID:${options.prodId ?? DEFAULT_PRODID}`,
126
+ "CALSCALE:GREGORIAN"
127
+ ];
128
+ if (options.method) lines.push(`METHOD:${options.method}`);
129
+ if (options.calendarName) lines.push(`X-WR-CALNAME:${escapeText(options.calendarName)}`);
130
+ const eventOptions = { ...options, dtstamp: stamp };
131
+ for (const event of events) {
132
+ lines.push(...veventLines(event, eventOptions));
133
+ }
134
+ lines.push("END:VCALENDAR");
135
+ return lines.map(foldLine).join("\r\n") + "\r\n";
136
+ }
137
+
138
+ export { defaultPriorityMap, escapeText, eventToVEvent, foldLine, toICS, veventLines };
package/package.json ADDED
@@ -0,0 +1,78 @@
1
+ {
2
+ "name": "calendaryjs-plugin-ics",
3
+ "version": "0.1.0",
4
+ "description": "ICS (RFC 5545) export for calendaryjs โ€” serialize generated calendar occurrences to a standard .ics VCALENDAR (VEVENT, VALARM reminders, PRIORITY, CATEGORIES, COLOR/IMAGE). The edge integration: calendaryjs owns the core, ICS rides at the boundary.",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "exports": {
8
+ ".": {
9
+ "import": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ },
13
+ "require": {
14
+ "types": "./dist/index.d.cts",
15
+ "default": "./dist/index.cjs"
16
+ }
17
+ }
18
+ },
19
+ "keywords": [
20
+ "ics",
21
+ "icalendar",
22
+ "rfc5545",
23
+ "vevent",
24
+ "vcalendar",
25
+ "export",
26
+ "calendar",
27
+ "calendaryjs",
28
+ "calendaryjs-plugin",
29
+ "plugin"
30
+ ],
31
+ "calendaryjs": {
32
+ "category": "integration"
33
+ },
34
+ "author": "calendaryjs",
35
+ "license": "MIT",
36
+ "peerDependencies": {
37
+ "calendaryjs": ">=0.1.0"
38
+ },
39
+ "devDependencies": {
40
+ "typescript": "^5.3.2",
41
+ "vitest": "^4.0.18",
42
+ "calendaryjs": "0.2.0"
43
+ },
44
+ "files": [
45
+ "dist"
46
+ ],
47
+ "tsup": {
48
+ "entry": [
49
+ "src/index.ts"
50
+ ],
51
+ "format": [
52
+ "esm",
53
+ "cjs"
54
+ ],
55
+ "dts": true,
56
+ "clean": true,
57
+ "treeshake": true
58
+ },
59
+ "repository": {
60
+ "type": "git",
61
+ "url": "git+https://github.com/calendaryjs/calendaryjs.git",
62
+ "directory": "packages/ics"
63
+ },
64
+ "homepage": "https://github.com/calendaryjs/calendaryjs/tree/main/packages/ics#readme",
65
+ "bugs": {
66
+ "url": "https://github.com/calendaryjs/calendaryjs/issues"
67
+ },
68
+ "scripts": {
69
+ "typecheck": "tsc --noEmit",
70
+ "test": "vitest run",
71
+ "test:watch": "vitest",
72
+ "build": "tsup",
73
+ "test:coverage": "vitest run --coverage"
74
+ },
75
+ "main": "./dist/index.cjs",
76
+ "module": "./dist/index.js",
77
+ "types": "./dist/index.d.ts"
78
+ }