@openpeepshq/common 0.11.0 → 0.13.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.
@@ -1,6 +1,26 @@
1
1
  import type { PublicPost } from '../types';
2
- export declare const buildEventIcs: (post: PublicPost, options?: {
2
+ /**
3
+ * Feed cache TTL in seconds. Single source of truth for the HTTP `max-age`
4
+ * and the ICS `REFRESH-INTERVAL`/`X-PUBLISHED-TTL` so they cannot drift.
5
+ */
6
+ export declare const EVENTS_ICS_FEED_TTL_SECONDS = 3600;
7
+ /**
8
+ * Minimal structural shape of an event post that the feed builder reads.
9
+ * `PostWithMeta` satisfies it, so callers can pass rich post objects
10
+ * without a cast.
11
+ */
12
+ export type IcsEventPost = {
13
+ id: string;
14
+ type: string;
15
+ data?: {
16
+ type?: string;
17
+ } & Record<string, unknown>;
18
+ updatedAt: string;
19
+ };
20
+ export declare const buildEventIcs: (post: IcsEventPost, options?: {
3
21
  postUrl?: string;
22
+ lastModified?: string;
23
+ sequence?: number;
4
24
  }) => string | null;
5
25
  /** Attendance ICS: discrete booked dates, or the series definition when none. */
6
26
  export declare const buildRsvpIcs: (post: PublicPost, options?: {
@@ -19,3 +39,23 @@ export declare const rsvpConfirmationContent: (post: PublicPost, options: {
19
39
  allDay: boolean;
20
40
  occurrenceCount: number;
21
41
  } | null;
42
+ /**
43
+ * Build a multi-event ICS feed string. Composes the single-event exports so
44
+ * the feed stays byte-identical to what the per-event download produces, and
45
+ * carries one deduped VTIMEZONE block per zone so zone-aware events survive.
46
+ *
47
+ * `postUrl` is the community base (origin); each event's joinable-URL fallback
48
+ * is derived as `${postUrl}/posts/{id}`, mirroring the single-event export.
49
+ * Passing a bare origin (never the request URL) keeps the feed's `?token=`
50
+ * secret out of the ICS body.
51
+ *
52
+ * With no events the feed is still a valid calendar (PRODID, `X-WR-CALNAME`,
53
+ * `REFRESH-INTERVAL`, `X-PUBLISHED-TTL`, no VEVENTs) — the same shape the
54
+ * feed endpoint's 401 `emptyCalendar` fallback mirrors. An empty feed is 200,
55
+ * not 404: calendar clients expect a parseable document they can re-poll.
56
+ */
57
+ export declare const buildEventsFeedIcs: (posts: IcsEventPost[], options: {
58
+ postUrl?: string;
59
+ name: string;
60
+ ttl?: number;
61
+ }) => string;
@@ -4,6 +4,11 @@ import { tzlib_get_ical_block } from 'timezones-ical-library';
4
4
  import { effectiveEventTimes } from './eventRecurrence.js';
5
5
  import { getJamUrl } from './jamHelpers.js';
6
6
  import { isIanaTimeZone } from './timeZone.js';
7
+ /**
8
+ * Feed cache TTL in seconds. Single source of truth for the HTTP `max-age`
9
+ * and the ICS `REFRESH-INTERVAL`/`X-PUBLISHED-TTL` so they cannot drift.
10
+ */
11
+ export const EVENTS_ICS_FEED_TTL_SECONDS = 3600;
7
12
  const utcDateFromYmd = (yyyyMmDd) => {
8
13
  const [y, m, d] = yyyyMmDd.split('-').map(Number);
9
14
  return new Date(Date.UTC(y, m - 1, d));
@@ -43,6 +48,32 @@ const withVtimezone = (calendarText, timeZone) => {
43
48
  normalized +
44
49
  calendarText.slice(veventIndex));
45
50
  };
51
+ /**
52
+ * ical-generator writes an all-day `recurrenceId` as a UTC instant
53
+ * (`RECURRENCE-ID:20260713T000000Z`), but RFC 5545 §3.8.4.4 requires the
54
+ * RECURRENCE-ID value type to match the series DTSTART — DATE for all-day
55
+ * events. Rewrite each RECURRENCE-ID line to DATE form.
56
+ */
57
+ const withDateRecurrenceId = (calendarText) =>
58
+ // Split on any line ending so a trailing `\r` is never carried into the
59
+ // re-joined CRLF text (splitting on `\n` alone would leave `\r\r\n`).
60
+ calendarText
61
+ .split(/\r\n|\r|\n/)
62
+ .map((line) => {
63
+ if (!line.startsWith('RECURRENCE-ID'))
64
+ return line;
65
+ if (line.includes(';VALUE=DATE'))
66
+ return line;
67
+ const colonIdx = line.indexOf(':');
68
+ if (colonIdx === -1)
69
+ return line;
70
+ const ymd = line
71
+ .slice(colonIdx + 1)
72
+ .replace(/[^0-9]/g, '')
73
+ .slice(0, 8);
74
+ return `RECURRENCE-ID;VALUE=DATE:${ymd}`;
75
+ })
76
+ .join('\r\n');
46
77
  const originFromUrl = (url) => {
47
78
  if (!url) {
48
79
  return undefined;
@@ -110,6 +141,14 @@ export const buildEventIcs = (post, options) => {
110
141
  method: ICalCalendarMethod.PUBLISH,
111
142
  scale: 'GREGORIAN',
112
143
  });
144
+ // Optional per-post edit stamp (used by the feed so clients update an
145
+ // existing UID instead of re-adding); omitted for single-event exports.
146
+ const stamp = options?.lastModified
147
+ ? {
148
+ lastModified: new Date(options.lastModified),
149
+ sequence: options.sequence ?? 0,
150
+ }
151
+ : {};
113
152
  const link = event.url ?? options?.postUrl;
114
153
  const summary = event.name?.trim() || 'Event';
115
154
  const description = event.content?.trim();
@@ -130,6 +169,7 @@ export const buildEventIcs = (post, options) => {
130
169
  ...(description ? { description } : {}),
131
170
  ...(location ? { location } : {}),
132
171
  ...(link ? { url: link } : {}),
172
+ ...stamp,
133
173
  ...(repeating ? { repeating } : {}),
134
174
  });
135
175
  }
@@ -147,30 +187,58 @@ export const buildEventIcs = (post, options) => {
147
187
  ...(description ? { description } : {}),
148
188
  ...(location ? { location } : {}),
149
189
  ...(link ? { url: link } : {}),
190
+ ...stamp,
150
191
  ...(repeating ? { repeating } : {}),
151
192
  });
152
193
  }
153
194
  for (const exception of event.exceptions ?? []) {
154
195
  if (exception.cancelled || !exception.start)
155
196
  continue;
156
- const start = instantInZone(exception.start, timeZone);
157
- const end = exception.end
158
- ? instantInZone(exception.end, timeZone)
159
- : defaultEnd(start, timeZone);
160
- calendar.createEvent({
161
- id: `openpeeps-event-${post.id}-${exception.recurrenceId}@openpeepshq`,
162
- start,
163
- end,
164
- ...(timeZone ? { timezone: timeZone } : {}),
165
- summary,
166
- ...(description ? { description } : {}),
167
- ...(location ? { location } : {}),
168
- ...(link ? { url: link } : {}),
169
- recurrenceId: instantInZone(exception.recurrenceId, timeZone),
170
- });
197
+ if (event.wholeDay) {
198
+ // Rescheduled all-day occurrence: an all-day override whose day range
199
+ // is the exception's new start day through its end day (inclusive).
200
+ // RECURRENCE-ID identifies the *original* occurrence (RFC 5545 3.8.4.4),
201
+ // while DTSTART/DTEND stay on the new days. The DATE-form RECURRENCE-ID
202
+ // is normalized after serialization.
203
+ const excStartYmd = exception.start.slice(0, 10);
204
+ const excLastInclusiveYmd = exception.end?.slice(0, 10) ?? excStartYmd;
205
+ calendar.createEvent({
206
+ id: `openpeeps-event-${post.id}-${exception.recurrenceId}@openpeepshq`,
207
+ allDay: true,
208
+ start: utcDateFromYmd(excStartYmd),
209
+ end: exclusiveEndAfterInclusiveDay(excLastInclusiveYmd),
210
+ summary,
211
+ ...(description ? { description } : {}),
212
+ ...(location ? { location } : {}),
213
+ ...(link ? { url: link } : {}),
214
+ ...stamp,
215
+ recurrenceId: utcDateFromYmd(exception.recurrenceId.slice(0, 10)),
216
+ });
217
+ }
218
+ else {
219
+ const start = instantInZone(exception.start, timeZone);
220
+ const end = exception.end
221
+ ? instantInZone(exception.end, timeZone)
222
+ : defaultEnd(start, timeZone);
223
+ calendar.createEvent({
224
+ id: `openpeeps-event-${post.id}-${exception.recurrenceId}@openpeepshq`,
225
+ start,
226
+ end,
227
+ ...(timeZone ? { timezone: timeZone } : {}),
228
+ summary,
229
+ ...(description ? { description } : {}),
230
+ ...(location ? { location } : {}),
231
+ ...(link ? { url: link } : {}),
232
+ ...stamp,
233
+ recurrenceId: instantInZone(exception.recurrenceId, timeZone),
234
+ });
235
+ }
171
236
  }
172
237
  const calendarText = calendar.toString();
173
- return ((timeZone ? withVtimezone(calendarText, timeZone) : calendarText) + '\r\n');
238
+ const processed = event.wholeDay
239
+ ? withDateRecurrenceId(calendarText)
240
+ : calendarText;
241
+ return (timeZone ? withVtimezone(processed, timeZone) : processed) + '\r\n';
174
242
  };
175
243
  const addOccurrenceEvent = (calendar, post, event, recurrenceId, options) => {
176
244
  const link = event.url ?? options?.postUrl;
@@ -254,3 +322,93 @@ export const rsvpConfirmationContent = (post, options) => {
254
322
  occurrenceCount: occurrenceIds.length,
255
323
  };
256
324
  };
325
+ /** Collect the VEVENT blocks from a full ICS document. */
326
+ const extractVevents = (ics) => {
327
+ const blocks = [];
328
+ let depth = 0;
329
+ let current = [];
330
+ for (const line of ics.split(/\r?\n/)) {
331
+ if (line.startsWith('BEGIN:VEVENT')) {
332
+ depth += 1;
333
+ current = [line];
334
+ }
335
+ else if (line.startsWith('END:VEVENT')) {
336
+ depth -= 1;
337
+ current.push(line);
338
+ if (depth === 0)
339
+ blocks.push(current.join('\r\n'));
340
+ }
341
+ else if (depth > 0) {
342
+ current.push(line);
343
+ }
344
+ }
345
+ return blocks;
346
+ };
347
+ /**
348
+ * The zone list referenced by a set of VEVENTs, in first-seen order. Each
349
+ * per-post export splices in the VTIMEZONEs its events use; a feed of several
350
+ * zone-aware events must keep one block per zone (ical-generator emits
351
+ * `TZID=` references without any VTIMEZONE of its own).
352
+ */
353
+ const referencedZones = (vevents) => {
354
+ const zones = [];
355
+ for (const vevent of vevents) {
356
+ for (const line of vevent.split('\r\n')) {
357
+ const match = line.match(/;TZID=([^:;]+)/);
358
+ if (match && !zones.includes(match[1])) {
359
+ zones.push(match[1]);
360
+ }
361
+ }
362
+ }
363
+ return zones;
364
+ };
365
+ /**
366
+ * Build a multi-event ICS feed string. Composes the single-event exports so
367
+ * the feed stays byte-identical to what the per-event download produces, and
368
+ * carries one deduped VTIMEZONE block per zone so zone-aware events survive.
369
+ *
370
+ * `postUrl` is the community base (origin); each event's joinable-URL fallback
371
+ * is derived as `${postUrl}/posts/{id}`, mirroring the single-event export.
372
+ * Passing a bare origin (never the request URL) keeps the feed's `?token=`
373
+ * secret out of the ICS body.
374
+ *
375
+ * With no events the feed is still a valid calendar (PRODID, `X-WR-CALNAME`,
376
+ * `REFRESH-INTERVAL`, `X-PUBLISHED-TTL`, no VEVENTs) — the same shape the
377
+ * feed endpoint's 401 `emptyCalendar` fallback mirrors. An empty feed is 200,
378
+ * not 404: calendar clients expect a parseable document they can re-poll.
379
+ */
380
+ export const buildEventsFeedIcs = (posts, options) => {
381
+ const { name, ttl = EVENTS_ICS_FEED_TTL_SECONDS } = options;
382
+ const calendar = ical({
383
+ prodId: '//OpenPeeps//Feed//EN',
384
+ method: ICalCalendarMethod.PUBLISH,
385
+ scale: 'GREGORIAN',
386
+ name,
387
+ ttl,
388
+ });
389
+ const base = options.postUrl?.replace(/\/+$/, '');
390
+ const vevents = [];
391
+ for (const post of posts) {
392
+ if (post.type !== 'event' || post.data?.type !== 'event')
393
+ continue;
394
+ const single = buildEventIcs(post, {
395
+ postUrl: base ? `${base}/posts/${post.id}` : undefined,
396
+ lastModified: post.updatedAt,
397
+ // Minutes since epoch: stable across processes, grows only on edits.
398
+ sequence: Math.floor(new Date(post.updatedAt).getTime() / 60000),
399
+ });
400
+ if (single)
401
+ vevents.push(...extractVevents(single));
402
+ }
403
+ const zoneBlocks = referencedZones(vevents)
404
+ .map((zone) => {
405
+ const [block] = tzlib_get_ical_block(zone);
406
+ return block.replace(/\r?\n/g, '\r\n').trim();
407
+ })
408
+ .join('\r\n');
409
+ const body = (zoneBlocks ? zoneBlocks + '\r\n' : '') +
410
+ (vevents.length ? vevents.join('\r\n') + '\r\n' : '');
411
+ return calendar
412
+ .toString()
413
+ .replace(/END:VCALENDAR\r?\n?$/, body + 'END:VCALENDAR\r\n');
414
+ };
@@ -1,4 +1,4 @@
1
- import { Answer, AnswerWithPublicProfile, AuthorizationData, CapabilitiesConfig, EntryWithPublicProfile, Event, GroupWithMeta, PostType, PostDataUnion, PublicPost, PublicProfile, PublicRsvp, RSVP, Thread, VisibilityType } from '../types';
1
+ import { Answer, AnswerWithPublicProfile, AuthorizationData, CapabilitiesConfig, EntryWithPublicProfile, Event, GroupWithMeta, PostType, PostDataUnion, PublicPost, PublicProfile, PublicRsvp, Role, RSVP, Thread, VisibilityType } from '../types';
2
2
  export declare const buildThreads: (posts: PublicPost[]) => Thread[];
3
3
  export type ThreadPreviewPost = {
4
4
  id: string;
@@ -261,6 +261,23 @@ export declare const parseEventMaxAttendeesInput: (raw: string) => number | unde
261
261
  export declare const normalizeWaitlistOfferMinutes: (value: number | null | undefined) => number | undefined;
262
262
  export declare const parseEventWaitlistOfferMinutesInput: (raw: string) => number | undefined;
263
263
  export declare const withoutEventMaxAttendees: <T extends Event>(event: T) => T;
264
+ /** A community-wide jam only broadcasts when the creator opted in. */
265
+ export declare const withoutJamNotifyEveryone: <T extends Event>(event: T) => T;
266
+ /**
267
+ * Broadcast requires community-wide visibility AND the announce capability
268
+ * (same rule as `POST /admin/posts/:postId/announce`); other visibilities or
269
+ * roles drop the flag. The capability check matters because the save path is
270
+ * reachable without the UI toggle: a plain member's role wildcard-matches
271
+ * `core-posts-create-*`, so a crafted API payload could otherwise plant the
272
+ * flag and blast the whole instance.
273
+ *
274
+ * Exported (rather than kept module-local) because `@openpeepshq/core`'s
275
+ * `createPost`/`updatePost` mutations apply it on the server-side save path;
276
+ * it is not a general-purpose utility — unlike `withoutJamNotifyEveryone` and
277
+ * `withoutEventMaxAttendees`, it takes the creator's roles in addition to the
278
+ * event.
279
+ */
280
+ export declare const withoutCommunityJamNotifyEveryone: <T extends Event>(event: T, visibility: string | undefined, roles?: Role[]) => T;
264
281
  export declare const normalizeEventDataForSave: <T extends Event>(event: T) => T;
265
282
  /** Null capacity means it was cleared; strip for validation/output. */
266
283
  export declare const normalizeEventDataFromDb: <T extends Event>(event: T) => T;
@@ -1,5 +1,6 @@
1
1
  import { POLL_OPTION_MAX_LENGTH, visibilityTypeValues, } from '../types/index.js';
2
2
  import { canModerateJam } from './jamHelpers.js';
3
+ import { canAnnouncePosts, isCommunityWideVisibility, } from './capabilitiesHelpers.js';
3
4
  import { defaultRsvpRecurrenceId, effectiveEventTimes, isRecurringEvent, listRsvpOccurrences, normalizeRecurrenceId, sameRecurrenceId, } from './eventRecurrence.js';
4
5
  import { formatEventWhen } from './eventTime.js';
5
6
  import { checkCapabilities, checkGroupCapabilities, checkPostCapabilities, checkRoleCapabilities, getGroupCapabilities, } from './capabilitiesHelpers.js';
@@ -368,6 +369,29 @@ export const withoutEventMaxAttendees = (event) => {
368
369
  const { maxAttendees: _, waitlistOfferMinutes: __, ...rest } = event;
369
370
  return rest;
370
371
  };
372
+ /** A community-wide jam only broadcasts when the creator opted in. */
373
+ export const withoutJamNotifyEveryone = (event) => {
374
+ if (!event.jam?.notifyEveryone)
375
+ return event;
376
+ return { ...event, jam: { ...event.jam, notifyEveryone: undefined } };
377
+ };
378
+ /**
379
+ * Broadcast requires community-wide visibility AND the announce capability
380
+ * (same rule as `POST /admin/posts/:postId/announce`); other visibilities or
381
+ * roles drop the flag. The capability check matters because the save path is
382
+ * reachable without the UI toggle: a plain member's role wildcard-matches
383
+ * `core-posts-create-*`, so a crafted API payload could otherwise plant the
384
+ * flag and blast the whole instance.
385
+ *
386
+ * Exported (rather than kept module-local) because `@openpeepshq/core`'s
387
+ * `createPost`/`updatePost` mutations apply it on the server-side save path;
388
+ * it is not a general-purpose utility — unlike `withoutJamNotifyEveryone` and
389
+ * `withoutEventMaxAttendees`, it takes the creator's roles in addition to the
390
+ * event.
391
+ */
392
+ export const withoutCommunityJamNotifyEveryone = (event, visibility, roles) => isCommunityWideVisibility(visibility) && canAnnouncePosts(roles)
393
+ ? event
394
+ : withoutJamNotifyEveryone(event);
371
395
  export const normalizeEventDataForSave = (event) => {
372
396
  const { maxAttendees } = event;
373
397
  if (maxAttendees == null ||