@vermeulen.solutions/eventual 0.0.0-stage → 0.18.2
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 +21 -0
- package/README.md +139 -2
- package/astro/EventList.astro +57 -0
- package/astro/admin.d.mts +3 -0
- package/astro/admin.mjs +158 -0
- package/astro/blueprint.d.mts +51 -0
- package/astro/blueprint.mjs +236 -0
- package/astro/cache.ts +82 -0
- package/astro/descriptor.mjs +7 -0
- package/astro/editor-compat.mjs +197 -0
- package/astro/editor-i18n.d.mts +8 -0
- package/astro/editor-i18n.mjs +157 -0
- package/astro/event-details.ts +29 -0
- package/astro/event-list.ts +56 -0
- package/astro/feed.ts +201 -0
- package/astro/install.d.mts +9 -0
- package/astro/install.mjs +66 -0
- package/astro/schema.ts +88 -0
- package/dist/index.d.mts +5 -0
- package/dist/index.mjs +1585 -0
- package/dist/plugin.d.mts +6 -0
- package/dist/plugin.mjs +13 -0
- package/docs/collection-setup.md +46 -0
- package/docs/history.md +16 -0
- package/docs/native-modernization.md +99 -0
- package/docs/public-feed-caching.md +259 -0
- package/docs/registry-installation.md +13 -0
- package/docs/release-notes-0.14.0.md +27 -0
- package/docs/release-notes-0.14.1.md +40 -0
- package/docs/release-notes-0.15.0.md +18 -0
- package/docs/release-notes-0.16.0.md +7 -0
- package/docs/release-notes-0.17.0.md +7 -0
- package/docs/release-notes-0.18.0.md +8 -0
- package/docs/release-notes-0.18.1.md +7 -0
- package/docs/release-notes-0.18.2.md +6 -0
- package/docs/upgrade-0.13.0.md +21 -0
- package/docs/user-guide.md +40 -0
- package/emdash-plugin.jsonc +77 -0
- package/package.json +143 -4
- package/scripts/check-editor-installation.mjs +32 -0
- package/scripts/export-native-schema.mjs +28 -0
- package/scripts/upgrade-native-editor.mjs +296 -0
- package/src/domain/calendar-links.ts +80 -0
- package/src/domain/category.ts +32 -0
- package/src/domain/collections.ts +101 -0
- package/src/domain/date-time.ts +220 -0
- package/src/domain/description.ts +108 -0
- package/src/domain/event-data.ts +217 -0
- package/src/domain/event-expansion.ts +305 -0
- package/src/domain/event.ts +195 -0
- package/src/domain/icalendar.ts +165 -0
- package/src/domain/image.ts +18 -0
- package/src/domain/invocation-budget.ts +56 -0
- package/src/domain/messages.ts +8 -0
- package/src/domain/migration.ts +666 -0
- package/src/domain/native-calendar.ts +256 -0
- package/src/domain/native-references.ts +41 -0
- package/src/domain/native-source.ts +261 -0
- package/src/domain/native-validation.ts +366 -0
- package/src/domain/occurrences.ts +54 -0
- package/src/domain/portable-text.ts +180 -0
- package/src/domain/public-cache.ts +24 -0
- package/src/domain/recurrence-rule.ts +34 -0
- package/src/domain/recurrence.ts +350 -0
- package/src/domain/request-memo.ts +8 -0
- package/src/domain/schedule-history.ts +14 -0
- package/src/domain/text.ts +2 -0
- package/src/domain/time-entry.ts +23 -0
- package/src/domain/venue-adapter.ts +101 -0
- package/src/domain/venue.ts +42 -0
- package/src/public-event.ts +88 -0
- package/src/schema/blueprint.ts +315 -0
- package/src/storage.ts +257 -0
- package/transfer/index.d.mts +13 -0
- package/transfer/index.mjs +155 -0
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { reject } from './messages';
|
|
2
|
+
import type { CollectionSchemaInfo } from 'emdash';
|
|
3
|
+
import type { EventualContext } from '../storage';
|
|
4
|
+
import {requestMemo, forgetRequestMemo} from './request-memo';
|
|
5
|
+
|
|
6
|
+
export interface CollectionBindings { events: string; venues: string; organizers: string }
|
|
7
|
+
export const COLLECTION_SETTINGS_KEY = 'collections';
|
|
8
|
+
export const LEGACY_READS_SETTING_KEY = 'legacyReads';
|
|
9
|
+
const slug = /^[a-z][a-z0-9_]{0,62}$/;
|
|
10
|
+
export async function eventCollectionName(ctx:EventualContext) {
|
|
11
|
+
return (await collectionSettings(ctx))?.events ?? 'events';
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function collectionSettings(ctx: EventualContext) {
|
|
15
|
+
return requestMemo(ctx, 'collection-settings', async () => await ctx.settings?.get<CollectionBindings>(COLLECTION_SETTINGS_KEY) ?? undefined);
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Private plugin storage holds pre-0.13 event records. Public reads only fall back to it
|
|
19
|
+
* when an administrator explicitly enables legacy reads; otherwise a site without a
|
|
20
|
+
* configured collection fails with an actionable error instead of serving stale data
|
|
21
|
+
* under the requested locale.
|
|
22
|
+
*/
|
|
23
|
+
export function legacyReadsEnabled(ctx: EventualContext) {
|
|
24
|
+
return requestMemo(ctx, 'legacy-reads', async () => (await ctx.settings?.get<boolean>(LEGACY_READS_SETTING_KEY)) === true);
|
|
25
|
+
}
|
|
26
|
+
export async function saveLegacyReadsSetting(ctx: EventualContext, enabled: boolean) {
|
|
27
|
+
await ctx.settings.set(LEGACY_READS_SETTING_KEY, enabled);
|
|
28
|
+
forgetRequestMemo(ctx, 'legacy-reads');
|
|
29
|
+
}
|
|
30
|
+
/** Raw discovery stays available when a selected collection needs repair. */
|
|
31
|
+
export function collectionSchemas(ctx: EventualContext) {
|
|
32
|
+
return requestMemo(ctx, 'schemas', async () => await ctx.schema?.listCollections() ?? []);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
interface LoadedCollectionBindings extends CollectionBindings {
|
|
36
|
+
schema: CollectionSchemaInfo | undefined;
|
|
37
|
+
schemas: CollectionSchemaInfo[];
|
|
38
|
+
configured: boolean;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function collectionBindings(ctx: EventualContext): Promise<LoadedCollectionBindings> {
|
|
42
|
+
return requestMemo(ctx, 'bindings', () => loadCollectionBindings(ctx));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Explicit selections fail closed. Removing a collection never revives legacy writes. */
|
|
46
|
+
async function loadCollectionBindings(ctx: EventualContext): Promise<LoadedCollectionBindings> {
|
|
47
|
+
const [selected, schemas] = await Promise.all([
|
|
48
|
+
collectionSettings(ctx),
|
|
49
|
+
collectionSchemas(ctx),
|
|
50
|
+
]);
|
|
51
|
+
if (selected && (!selected.events || Object.values(selected).some(value => typeof value !== 'string' || (value !== '' && !slug.test(value)))))
|
|
52
|
+
reject('Invalid collections. Choose them again in Event settings.');
|
|
53
|
+
const events = selected?.events ?? 'events';
|
|
54
|
+
const schema = schemas.find(item => item.slug === events);
|
|
55
|
+
if (selected && !schema) reject('The selected event collection is missing.');
|
|
56
|
+
const target = (field: string, fallback: string) => {
|
|
57
|
+
const definition = schema?.fields?.find(item => item.slug === field);
|
|
58
|
+
return String(definition?.validation?.targetCollection ?? definition?.options?.collection ?? fallback);
|
|
59
|
+
};
|
|
60
|
+
const bindings: CollectionBindings = {
|
|
61
|
+
events,
|
|
62
|
+
venues: selected?.venues ?? target('venue', 'venues'),
|
|
63
|
+
organizers: selected?.organizers ?? target('organizer_ref', 'organizers'),
|
|
64
|
+
};
|
|
65
|
+
if(selected) for(const name of [bindings.venues,bindings.organizers])
|
|
66
|
+
if(name && !schemas.some(item=>item.slug===name)) reject('Selected directory missing. Review Event settings.');
|
|
67
|
+
return { ...bindings, schema, schemas, configured: !!selected };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Validate before storing all three choices atomically as a single setting. */
|
|
71
|
+
export async function saveCollectionBindings(ctx: EventualContext, bindings: CollectionBindings) {
|
|
72
|
+
if (!bindings.events || Object.values(bindings).some(value => typeof value !== 'string' || (value !== '' && !slug.test(value))))
|
|
73
|
+
reject('Choose valid collection names.');
|
|
74
|
+
const schemas = await collectionSchemas(ctx);
|
|
75
|
+
const schema = schemas.find(item => item.slug === bindings.events);
|
|
76
|
+
if (!schema) reject('Choose an existing event collection.');
|
|
77
|
+
const required: Record<string, string> = {title:'string', description:'portableText', start:'datetime', end:'datetime', start_date:'string', end_date:'string', all_day:'boolean', timezone:'string', recurrence:'json', exceptions:'json', occurrence_content:'json'};
|
|
78
|
+
for (const [name, type] of Object.entries(required)) {
|
|
79
|
+
const field = schema.fields.find(item => item.slug === name);
|
|
80
|
+
if (!field || field.type !== type) reject('Event collection needs '+name+' ('+type+'). Apply the event blueprint first.');
|
|
81
|
+
const translatable = ['title','description','occurrence_content'].includes(name);
|
|
82
|
+
if (field.translatable !== translatable) reject('Set '+name+' translatable to '+translatable+' before selecting this collection.');
|
|
83
|
+
}
|
|
84
|
+
for (const [key, fieldName] of [['venues','venue'],['organizers','organizer_ref']] as const) {
|
|
85
|
+
const selected = bindings[key];
|
|
86
|
+
const directory = schemas.find(item => item.slug === selected);
|
|
87
|
+
if (selected && (!directory || !directory.fields.some(item => ['name','title'].includes(item.slug) && item.type === 'string')))
|
|
88
|
+
reject('Choose a '+key+' collection with a name or title field.');
|
|
89
|
+
const field = schema.fields.find(item => item.slug === fieldName);
|
|
90
|
+
const reference = schema.fields.find(item => item.slug === (field?.validation?.relation ? key === 'venues' ? 'venue_id' : 'organizer_id' : fieldName));
|
|
91
|
+
const target = reference?.validation?.targetCollection ?? reference?.options?.collection;
|
|
92
|
+
if (selected && (reference?.type !== 'reference' || target !== selected))
|
|
93
|
+
reject('Set the event '+fieldName+' reference target to '+selected+' first.');
|
|
94
|
+
if (!selected && reference) reject('This event schema has a '+fieldName+' reference. Select its target collection.');
|
|
95
|
+
if (reference?.translatable !== undefined && reference.translatable !== false)
|
|
96
|
+
reject('Event references must be shared across languages.');
|
|
97
|
+
}
|
|
98
|
+
await ctx.settings.set(COLLECTION_SETTINGS_KEY, bindings);
|
|
99
|
+
forgetRequestMemo(ctx, 'collection-settings');
|
|
100
|
+
forgetRequestMemo(ctx, 'bindings');
|
|
101
|
+
}
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import { TIMEZONE_ERROR, TIMEZONE_UNAVAILABLE, DST_ERROR } from './messages';
|
|
2
|
+
export interface DateValidationError {
|
|
3
|
+
start?: string;
|
|
4
|
+
end?: string;
|
|
5
|
+
timezone?: string;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface NormalizedDates {
|
|
9
|
+
start: string;
|
|
10
|
+
end: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
interface DateParts {
|
|
14
|
+
year: number;
|
|
15
|
+
month: number;
|
|
16
|
+
day: number;
|
|
17
|
+
hour: number;
|
|
18
|
+
minute: number;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function daysInMonth(year: number, month: number): number {
|
|
22
|
+
const date = new Date(0);
|
|
23
|
+
date.setUTCFullYear(year, month, 0);
|
|
24
|
+
return date.getUTCDate();
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function parseDate(value: string): DateParts | null {
|
|
28
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
|
|
29
|
+
if (!match) return null;
|
|
30
|
+
const year = Number(match[1]);
|
|
31
|
+
const month = Number(match[2]);
|
|
32
|
+
const day = Number(match[3]);
|
|
33
|
+
if (month < 1 || month > 12 || day < 1 || day > daysInMonth(year, month)) {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
return { year, month, day, hour: 0, minute: 0 };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function parseWallDateTime(value: string): DateParts | null {
|
|
40
|
+
const match = /^(\d{4}-\d{2}-\d{2})T(\d{2}):(\d{2})$/.exec(value);
|
|
41
|
+
const date = match ? parseDate(match[1]!) : null;
|
|
42
|
+
if (!date || !match) return null;
|
|
43
|
+
const hour = Number(match[2]);
|
|
44
|
+
const minute = Number(match[3]);
|
|
45
|
+
if (hour > 23 || minute > 59) return null;
|
|
46
|
+
return { ...date, hour, minute };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const zoneFormatters = new Map<string, Intl.DateTimeFormat>();
|
|
50
|
+
function partsInZone(instant: Date, timezone: string): DateParts | null {
|
|
51
|
+
try {
|
|
52
|
+
let formatter = zoneFormatters.get(timezone);
|
|
53
|
+
if (!formatter) {
|
|
54
|
+
formatter = new Intl.DateTimeFormat("en", {
|
|
55
|
+
timeZone: timezone,
|
|
56
|
+
calendar: "gregory",
|
|
57
|
+
numberingSystem: "latn",
|
|
58
|
+
year: "numeric",
|
|
59
|
+
month: "2-digit",
|
|
60
|
+
day: "2-digit",
|
|
61
|
+
hour: "2-digit",
|
|
62
|
+
minute: "2-digit",
|
|
63
|
+
hourCycle: "h23",
|
|
64
|
+
});
|
|
65
|
+
if (zoneFormatters.size >= 128) zoneFormatters.delete(zoneFormatters.keys().next().value!);
|
|
66
|
+
zoneFormatters.set(timezone,formatter);
|
|
67
|
+
}
|
|
68
|
+
const parts = formatter.formatToParts(instant);
|
|
69
|
+
const get = (type: Intl.DateTimeFormatPartTypes) =>
|
|
70
|
+
Number(parts.find((part) => part.type === type)?.value);
|
|
71
|
+
const result = {
|
|
72
|
+
year: get("year"),
|
|
73
|
+
month: get("month"),
|
|
74
|
+
day: get("day"),
|
|
75
|
+
hour: get("hour"),
|
|
76
|
+
minute: get("minute"),
|
|
77
|
+
};
|
|
78
|
+
return Object.values(result).every(Number.isFinite) ? result : null;
|
|
79
|
+
} catch {
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function utcEpoch(parts: DateParts): number {
|
|
85
|
+
const date = new Date(0);
|
|
86
|
+
date.setUTCFullYear(parts.year, parts.month - 1, parts.day);
|
|
87
|
+
date.setUTCHours(parts.hour, parts.minute, 0, 0);
|
|
88
|
+
return date.getTime();
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function sameParts(left: DateParts, right: DateParts): boolean {
|
|
92
|
+
return (
|
|
93
|
+
left.year === right.year &&
|
|
94
|
+
left.month === right.month &&
|
|
95
|
+
left.day === right.day &&
|
|
96
|
+
left.hour === right.hour &&
|
|
97
|
+
left.minute === right.minute
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function isDateOnly(value: string): boolean {
|
|
102
|
+
return parseDate(value) !== null;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Date-only arithmetic shared by public and administrative feed windows. */
|
|
106
|
+
export function addCalendarDays(value: string, count: number): string {
|
|
107
|
+
const date = new Date(`${value}T00:00:00Z`);
|
|
108
|
+
date.setUTCDate(date.getUTCDate() + count);
|
|
109
|
+
return date.toISOString().slice(0, 10);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function isValidTimeZone(timezone: string): boolean {
|
|
113
|
+
if (!timezone.trim()) return false;
|
|
114
|
+
try {
|
|
115
|
+
new Intl.DateTimeFormat("en", { timeZone: timezone });
|
|
116
|
+
return true;
|
|
117
|
+
} catch {
|
|
118
|
+
return false;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function browserTimeZone(): string {
|
|
123
|
+
return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Converts a local wall-clock value to an ISO instant in an IANA timezone. */
|
|
127
|
+
export function localDateTimeToInstant(
|
|
128
|
+
value: string,
|
|
129
|
+
timezone: string,
|
|
130
|
+
): { value?: string; error?: string } {
|
|
131
|
+
const desired = parseWallDateTime(value);
|
|
132
|
+
if (!desired) return { error: "Enter a valid date and time." };
|
|
133
|
+
if (!isValidTimeZone(timezone)) {
|
|
134
|
+
return { error: TIMEZONE_ERROR };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const wantedEpoch = utcEpoch(desired);
|
|
138
|
+
const possibleInstants = new Set<number>();
|
|
139
|
+
let timezoneWorked = false;
|
|
140
|
+
// Sampling on both sides of a transition discovers either valid offset in a
|
|
141
|
+
// repeated wall-clock hour. Choosing the earliest exact match preserves
|
|
142
|
+
// Eventual's fall-back rule without treating clock-gap times as valid.
|
|
143
|
+
for (let hours = -36; hours <= 36; hours += 3) {
|
|
144
|
+
const probe = wantedEpoch + hours * 3_600_000;
|
|
145
|
+
const actual = partsInZone(new Date(probe), timezone);
|
|
146
|
+
if (!actual) continue;
|
|
147
|
+
timezoneWorked = true;
|
|
148
|
+
const offset = utcEpoch(actual) - probe;
|
|
149
|
+
const candidate = wantedEpoch - offset;
|
|
150
|
+
const candidateParts = partsInZone(new Date(candidate), timezone);
|
|
151
|
+
if (candidateParts && sameParts(candidateParts, desired)) possibleInstants.add(candidate);
|
|
152
|
+
}
|
|
153
|
+
if (!timezoneWorked) {
|
|
154
|
+
return { error: TIMEZONE_UNAVAILABLE };
|
|
155
|
+
}
|
|
156
|
+
if (possibleInstants.size) {
|
|
157
|
+
return { value: new Date(Math.min(...possibleInstants)).toISOString() };
|
|
158
|
+
}
|
|
159
|
+
{
|
|
160
|
+
return {
|
|
161
|
+
error: DST_ERROR,
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export function instantToLocalDateTime(value: string, timezone: string): string {
|
|
167
|
+
const instant = new Date(value);
|
|
168
|
+
if (Number.isNaN(instant.getTime()) || !isValidTimeZone(timezone)) return "";
|
|
169
|
+
const parts = partsInZone(instant, timezone);
|
|
170
|
+
if (!parts) return "";
|
|
171
|
+
const pad = (part: number) => String(part).padStart(2, "0");
|
|
172
|
+
return `${String(parts.year).padStart(4, "0")}-${pad(parts.month)}-${pad(parts.day)}T${pad(parts.hour)}:${pad(parts.minute)}`;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export function calendarDateKey(
|
|
176
|
+
value: string,
|
|
177
|
+
allDay: boolean,
|
|
178
|
+
timezone: string,
|
|
179
|
+
): string {
|
|
180
|
+
if (allDay) return isDateOnly(value) ? value : "";
|
|
181
|
+
const instant = new Date(value);
|
|
182
|
+
if (Number.isNaN(instant.getTime())) return "";
|
|
183
|
+
const parts = partsInZone(instant, isValidTimeZone(timezone) ? timezone : "UTC");
|
|
184
|
+
if (!parts) return "";
|
|
185
|
+
return `${String(parts.year).padStart(4, "0")}-${String(parts.month).padStart(2, "0")}-${String(parts.day).padStart(2, "0")}`;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export function normalizeEventDates(input: {
|
|
189
|
+
start: string;
|
|
190
|
+
end: string;
|
|
191
|
+
allDay: boolean;
|
|
192
|
+
timezone: string;
|
|
193
|
+
}): { dates?: NormalizedDates; errors: DateValidationError } {
|
|
194
|
+
const errors: DateValidationError = {};
|
|
195
|
+
if (input.allDay) {
|
|
196
|
+
if (!isDateOnly(input.start)) errors.start = "Choose a valid start date.";
|
|
197
|
+
if (!isDateOnly(input.end)) errors.end = "Choose a valid end date.";
|
|
198
|
+
if (!errors.start && !errors.end && input.end < input.start) {
|
|
199
|
+
errors.end = "The end must be on or after the start.";
|
|
200
|
+
}
|
|
201
|
+
return Object.keys(errors).length
|
|
202
|
+
? { errors }
|
|
203
|
+
: { dates: { start: input.start, end: input.end }, errors };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
if (!isValidTimeZone(input.timezone)) {
|
|
207
|
+
errors.timezone = TIMEZONE_ERROR;
|
|
208
|
+
return { errors };
|
|
209
|
+
}
|
|
210
|
+
const start = localDateTimeToInstant(input.start, input.timezone);
|
|
211
|
+
const end = localDateTimeToInstant(input.end, input.timezone);
|
|
212
|
+
if (!start.value) errors.start = start.error;
|
|
213
|
+
if (!end.value) errors.end = end.error;
|
|
214
|
+
if (start.value && end.value && Date.parse(end.value) < Date.parse(start.value)) {
|
|
215
|
+
errors.end = "The end must be on or after the start.";
|
|
216
|
+
}
|
|
217
|
+
return Object.keys(errors).length
|
|
218
|
+
? { errors }
|
|
219
|
+
: { dates: { start: start.value!, end: end.value! }, errors };
|
|
220
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/** The small formatting vocabulary supported by the sandbox description editor. */
|
|
2
|
+
export type DescriptionBlockStyle = "paragraph" | "heading" | "bullet" | "bold" | "italic";
|
|
3
|
+
export interface DescriptionBlock {
|
|
4
|
+
style: DescriptionBlockStyle;
|
|
5
|
+
text: string;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export const MAX_DESCRIPTION_BLOCKS = 12;
|
|
9
|
+
const STYLES = ["paragraph", "heading", "bullet", "bold", "italic"];
|
|
10
|
+
|
|
11
|
+
function decodeText(value: string): string {
|
|
12
|
+
return value.replace(/&(#x[\da-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi, (entity, code: string) => {
|
|
13
|
+
if (code[0] === "#") {
|
|
14
|
+
const numeric = code[1]?.toLowerCase() === "x" ? Number.parseInt(code.slice(2), 16) : Number.parseInt(code.slice(1), 10);
|
|
15
|
+
return Number.isFinite(numeric) && numeric > 0 && numeric <= 0x10ffff && !(numeric >= 0xd800 && numeric <= 0xdfff)
|
|
16
|
+
? String.fromCodePoint(numeric) : "�";
|
|
17
|
+
}
|
|
18
|
+
return ({ amp: "&", lt: "<", gt: ">", quot: "\"", apos: "'", nbsp: "\u00a0" } as Record<string, string>)[code.toLowerCase()] ?? entity;
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function inlineText(value: string): string | null {
|
|
23
|
+
const text = value.replace(/<br\s*\/?\s*>/gi, "\n");
|
|
24
|
+
return /[<>]/.test(text) ? null : decodeText(text);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Reopen our own HTML output. Unsupported markup is left untouched, never flattened. */
|
|
28
|
+
export function readDescription(description: string): { blocks: DescriptionBlock[]; editable: boolean } {
|
|
29
|
+
if (!description.trim()) return { blocks: [], editable: true };
|
|
30
|
+
if (!/<\/?[a-z!][^>]*>/i.test(description)) {
|
|
31
|
+
return { blocks: [{ style: "paragraph", text: description }], editable: description.length <= 5000 };
|
|
32
|
+
}
|
|
33
|
+
const blocks: DescriptionBlock[] = [];
|
|
34
|
+
let end = 0;
|
|
35
|
+
for (const match of description.matchAll(/<(p|h3|ul)>([\s\S]*?)<\/\1>/g)) {
|
|
36
|
+
if (description.slice(end, match.index).trim()) return { blocks: [], editable: false };
|
|
37
|
+
end = match.index + match[0].length;
|
|
38
|
+
const tag = match[1]!;
|
|
39
|
+
let body = match[2]!;
|
|
40
|
+
let style: DescriptionBlockStyle = tag === "h3" ? "heading" : tag === "ul" ? "bullet" : "paragraph";
|
|
41
|
+
let text: string | null;
|
|
42
|
+
if (tag === "ul") {
|
|
43
|
+
const items: string[] = [];
|
|
44
|
+
let listEnd = 0;
|
|
45
|
+
for (const item of body.matchAll(/<li>([\s\S]*?)<\/li>/g)) {
|
|
46
|
+
const content = inlineText(item[1]!);
|
|
47
|
+
if (body.slice(listEnd, item.index).trim() || content === null || content.includes("\n")) return { blocks: [], editable: false };
|
|
48
|
+
items.push(content);
|
|
49
|
+
listEnd = item.index + item[0].length;
|
|
50
|
+
}
|
|
51
|
+
if (!items.length || body.slice(listEnd).trim() || items.length > 100) return { blocks: [], editable: false };
|
|
52
|
+
text = items.join("\n");
|
|
53
|
+
} else {
|
|
54
|
+
const emphasis = /^<(strong|em)>([\s\S]*)<\/\1>$/.exec(body);
|
|
55
|
+
if (tag === "p" && emphasis) {
|
|
56
|
+
style = emphasis[1] === "strong" ? "bold" : "italic";
|
|
57
|
+
body = emphasis[2]!;
|
|
58
|
+
}
|
|
59
|
+
text = inlineText(body);
|
|
60
|
+
}
|
|
61
|
+
if (text === null || text.length > 5000) return { blocks: [], editable: false };
|
|
62
|
+
blocks.push({ style, text });
|
|
63
|
+
}
|
|
64
|
+
return description.slice(end).trim() || !blocks.length || blocks.length > MAX_DESCRIPTION_BLOCKS
|
|
65
|
+
? { blocks: [], editable: false } : { blocks, editable: true };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function escapeText(value: string): string {
|
|
69
|
+
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Safely serialize an ordered description. A complete list occupies one section. */
|
|
73
|
+
export function blocksToDescription(value: unknown): { description?: string; error?: string } {
|
|
74
|
+
if (!Array.isArray(value) || value.length > MAX_DESCRIPTION_BLOCKS) return { error: `A description can have up to ${MAX_DESCRIPTION_BLOCKS} sections.` };
|
|
75
|
+
const html: string[] = [];
|
|
76
|
+
for (const item of value) {
|
|
77
|
+
if (typeof item !== "object" || item === null || Array.isArray(item)) return { error: "Check the description text and formatting." };
|
|
78
|
+
const block = item as Record<string, unknown>;
|
|
79
|
+
if (typeof block.text !== "string" || typeof block.style !== "string" || !STYLES.includes(block.style)) return { error: "Choose a valid format and enter ordinary text." };
|
|
80
|
+
if (block.text.length > 5000) return { error: "Keep each section to 5,000 characters or fewer. Split longer text into another paragraph." };
|
|
81
|
+
const text = block.text.replace(/\r\n?/g, "\n").trim();
|
|
82
|
+
if (!text) continue;
|
|
83
|
+
if (block.style === "bullet") {
|
|
84
|
+
const items = text.split("\n").map((line) => line.trim()).filter(Boolean);
|
|
85
|
+
if (items.length > 100) return { error: "A list can have up to 100 items. Split longer lists into another section." };
|
|
86
|
+
html.push(`<ul>${items.map((line) => `<li>${escapeText(line)}</li>`).join("")}</ul>`);
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
const content = escapeText(text).replace(/\n/g, "<br>");
|
|
90
|
+
if (block.style === "heading") html.push(`<h3>${content}</h3>`);
|
|
91
|
+
else if (block.style === "bold") html.push(`<p><strong>${content}</strong></p>`);
|
|
92
|
+
else if (block.style === "italic") html.push(`<p><em>${content}</em></p>`);
|
|
93
|
+
else html.push(`<p>${content}</p>`);
|
|
94
|
+
}
|
|
95
|
+
const description = html.join(" ");
|
|
96
|
+
return new TextEncoder().encode(description).byteLength > 60000
|
|
97
|
+
? { error: "The description is too long. Shorten it before saving." } : { description };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function descriptionInput(values: Record<string, unknown>): { block?: DescriptionBlock; error?: string } {
|
|
101
|
+
if (typeof values.text !== "string" || !values.text.trim()) return { error: "Enter some text, or choose Cancel to return to the description." };
|
|
102
|
+
if (typeof values.kind !== "string" || !["paragraph", "heading", "bullet"].includes(values.kind)) return { error: "Choose Paragraph, Heading, or Bullet list." };
|
|
103
|
+
if (values.kind === "paragraph" && (typeof values.emphasis !== "string" || !["normal", "bold", "italic"].includes(values.emphasis))) return { error: "Choose Normal, Bold, or Italic text." };
|
|
104
|
+
const style = values.kind === "paragraph" && values.emphasis !== "normal" ? values.emphasis : values.kind;
|
|
105
|
+
const block = { style: style as DescriptionBlockStyle, text: values.text };
|
|
106
|
+
const result = blocksToDescription([block]);
|
|
107
|
+
return result.error ? { error: result.error } : { block };
|
|
108
|
+
}
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import { EXTERNAL_URL_ERROR } from './messages';
|
|
2
|
+
import { instantToLocalDateTime, isDateOnly, normalizeEventDates } from "./date-time";
|
|
3
|
+
import { normalizeCategories } from "./category";
|
|
4
|
+
import type {
|
|
5
|
+
EventDraft,
|
|
6
|
+
EventStatus,
|
|
7
|
+
EventFields,
|
|
8
|
+
EventRecurrence,
|
|
9
|
+
EventRecord,
|
|
10
|
+
MonthlyPosition,
|
|
11
|
+
WeekdayName,
|
|
12
|
+
} from "./event";
|
|
13
|
+
import { safeHttpUrl } from "./venue";
|
|
14
|
+
import { normalizeWeekdays, validRecurrence } from "./recurrence-rule";
|
|
15
|
+
|
|
16
|
+
const WEEKDAYS: WeekdayName[] = [
|
|
17
|
+
"sunday",
|
|
18
|
+
"monday",
|
|
19
|
+
"tuesday",
|
|
20
|
+
"wednesday",
|
|
21
|
+
"thursday",
|
|
22
|
+
"friday",
|
|
23
|
+
"saturday",
|
|
24
|
+
];
|
|
25
|
+
|
|
26
|
+
function dateParts(value: string): [number, number, number] {
|
|
27
|
+
return value.slice(0, 10).split("-").map(Number) as [number, number, number];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function weekdayForDate(value: string): WeekdayName {
|
|
31
|
+
const [year, month, day] = dateParts(value);
|
|
32
|
+
return WEEKDAYS[new Date(Date.UTC(year, month - 1, day)).getUTCDay()]!;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function monthlyPositionForDate(value: string): MonthlyPosition {
|
|
36
|
+
const [, , day] = dateParts(value);
|
|
37
|
+
return Math.ceil(day / 7) as MonthlyPosition;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function isLastWeekdayOfMonth(value: string): boolean {
|
|
41
|
+
const [year, month, day] = dateParts(value);
|
|
42
|
+
const date = new Date(Date.UTC(year, month - 1, day + 7));
|
|
43
|
+
return date.getUTCMonth() !== month - 1 || date.getUTCFullYear() !== year;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function recurrenceForDraft(draft: EventDraft): EventRecurrence | undefined {
|
|
47
|
+
if (draft.repeatFrequency === "none") return undefined;
|
|
48
|
+
const schedule = { until: draft.recurrenceUntil, ...(draft.recurrenceInterval !== undefined && draft.recurrenceInterval !== 1 ? { interval: draft.recurrenceInterval } : {}) };
|
|
49
|
+
if (draft.repeatFrequency === "daily" || draft.repeatFrequency === "weekly") {
|
|
50
|
+
return { frequency: draft.repeatFrequency, ...schedule, ...(draft.repeatFrequency === "weekly" && draft.weeklyWeekdays?.length
|
|
51
|
+
? { weekdays: normalizeWeekdays(draft.weeklyWeekdays) } : {}) };
|
|
52
|
+
}
|
|
53
|
+
return {
|
|
54
|
+
frequency: "monthly",
|
|
55
|
+
...schedule,
|
|
56
|
+
pattern:
|
|
57
|
+
draft.monthlyPattern === "dayOfMonth"
|
|
58
|
+
? {
|
|
59
|
+
type: "dayOfMonth",
|
|
60
|
+
dayOfMonth: draft.monthlyDayOfMonth ?? Number(draft.start.slice(8, 10)),
|
|
61
|
+
missingDayBehavior: draft.missingDayBehavior,
|
|
62
|
+
}
|
|
63
|
+
: {
|
|
64
|
+
type: "weekdayOfMonth",
|
|
65
|
+
weekday: draft.monthlyWeekday,
|
|
66
|
+
position: draft.monthlyPosition,
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Visibility is authoritative; lifecycle states only apply to published events. */
|
|
72
|
+
export function normalizeEventStatus(published: boolean, status?: EventStatus): EventStatus {
|
|
73
|
+
return !published ? "draft" : !status || status === "draft" ? "published" : status;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function prepareEventData(
|
|
77
|
+
draft: EventDraft,
|
|
78
|
+
/** Only for storage import callers that already validated canonical schedules. */
|
|
79
|
+
validatedDates?: { start: string; end: string },
|
|
80
|
+
): { data?: EventFields & { recurrence?: EventRecurrence; exceptions: EventRecord["exceptions"] }; error?: string } {
|
|
81
|
+
const title = draft.title.trim();
|
|
82
|
+
if (!title) return { error: "Event title is required." };
|
|
83
|
+
if (draft.externalUrl.trim() && !safeHttpUrl(draft.externalUrl)) {
|
|
84
|
+
return { error: EXTERNAL_URL_ERROR };
|
|
85
|
+
}
|
|
86
|
+
if (draft.virtualUrl?.trim() && !safeHttpUrl(draft.virtualUrl)) {
|
|
87
|
+
return { error: "Virtual URL must use HTTP or HTTPS." };
|
|
88
|
+
}
|
|
89
|
+
if (draft.imageUrl.trim() && !safeHttpUrl(draft.imageUrl)) {
|
|
90
|
+
return { error: "Image URL must use HTTP or HTTPS." };
|
|
91
|
+
}
|
|
92
|
+
const normalized = validatedDates ? { dates: validatedDates, errors: {} } : normalizeEventDates({
|
|
93
|
+
start: draft.start,
|
|
94
|
+
end: draft.end,
|
|
95
|
+
allDay: draft.allDay,
|
|
96
|
+
timezone: draft.timezone,
|
|
97
|
+
});
|
|
98
|
+
if (!normalized.dates) {
|
|
99
|
+
return { error: normalized.errors.start ?? normalized.errors.end ?? normalized.errors.timezone ?? "Check the event dates." };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const startDate = draft.start.slice(0, 10);
|
|
103
|
+
const recurrence = recurrenceForDraft(draft);
|
|
104
|
+
if (recurrence && !validRecurrence(recurrence)) return { error: "Choose a valid repeat pattern and an integer interval from 1 through 52." };
|
|
105
|
+
if (recurrence?.frequency === "weekly" && recurrence.weekdays && !recurrence.weekdays.includes(weekdayForDate(startDate))) {
|
|
106
|
+
return { error: "The first event must fall on one of the selected weekly days." };
|
|
107
|
+
}
|
|
108
|
+
if (recurrence && (!isDateOnly(recurrence.until) || recurrence.until < startDate)) {
|
|
109
|
+
return { error: "Choose a recurrence end date on or after the first event." };
|
|
110
|
+
}
|
|
111
|
+
if (
|
|
112
|
+
recurrence?.frequency === "monthly" &&
|
|
113
|
+
recurrence.pattern.type === "weekdayOfMonth" &&
|
|
114
|
+
(weekdayForDate(startDate) !== recurrence.pattern.weekday ||
|
|
115
|
+
(recurrence.pattern.position === "last"
|
|
116
|
+
? !isLastWeekdayOfMonth(startDate)
|
|
117
|
+
: monthlyPositionForDate(startDate) !== recurrence.pattern.position))
|
|
118
|
+
) {
|
|
119
|
+
return { error: "The first event must match the selected monthly weekday pattern." };
|
|
120
|
+
}
|
|
121
|
+
if (recurrence?.frequency === "monthly" && recurrence.pattern.type === "dayOfMonth") {
|
|
122
|
+
const [year, month, day] = dateParts(startDate);
|
|
123
|
+
const last = new Date(Date.UTC(year, month, 0)).getUTCDate();
|
|
124
|
+
const target = recurrence.pattern.missingDayBehavior === "lastDay" ? Math.min(recurrence.pattern.dayOfMonth, last) : recurrence.pattern.dayOfMonth;
|
|
125
|
+
if (day !== target) return { error: "The first event must match the selected monthly day and missing-day policy." };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const categories = normalizeCategories(draft.categories);
|
|
129
|
+
const mediaId = (draft.featuredMediaId || draft.imageMediaId || "").trim();
|
|
130
|
+
return {
|
|
131
|
+
data: {
|
|
132
|
+
title,
|
|
133
|
+
description: draft.description.trim(),
|
|
134
|
+
...normalized.dates,
|
|
135
|
+
allDay: draft.allDay,
|
|
136
|
+
timezone: draft.timezone.trim(),
|
|
137
|
+
location: draft.location.trim(),
|
|
138
|
+
locationType: draft.locationType ?? "physical",
|
|
139
|
+
...(draft.virtualUrl?.trim() ? { virtualUrl: safeHttpUrl(draft.virtualUrl) } : {}),
|
|
140
|
+
status: normalizeEventStatus(draft.published, draft.status),
|
|
141
|
+
organizer: draft.organizer.trim(),
|
|
142
|
+
...(draft.organizerId ? { organizerId: draft.organizerId } : {}),
|
|
143
|
+
externalUrl: safeHttpUrl(draft.externalUrl),
|
|
144
|
+
imageUrl: mediaId ? "" : safeHttpUrl(draft.imageUrl),
|
|
145
|
+
...(mediaId ? { imageMediaId: mediaId, featuredMediaId: mediaId } : {}),
|
|
146
|
+
categories,
|
|
147
|
+
...(draft.venueId ? { venueId: draft.venueId } : {}),
|
|
148
|
+
published: draft.published,
|
|
149
|
+
...(recurrence ? { recurrence } : {}),
|
|
150
|
+
exceptions: draft.exceptions,
|
|
151
|
+
},
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export function eventToDraft(event: EventRecord): EventDraft {
|
|
156
|
+
const timezone = event.timezone || "UTC";
|
|
157
|
+
const start = event.allDay
|
|
158
|
+
? event.start.slice(0, 10)
|
|
159
|
+
: instantToLocalDateTime(event.start, timezone);
|
|
160
|
+
const end = event.allDay
|
|
161
|
+
? event.end.slice(0, 10)
|
|
162
|
+
: instantToLocalDateTime(event.end, timezone);
|
|
163
|
+
const recurrence = event.recurrence;
|
|
164
|
+
return {
|
|
165
|
+
title: event.title,
|
|
166
|
+
description: event.description,
|
|
167
|
+
start,
|
|
168
|
+
end,
|
|
169
|
+
allDay: event.allDay,
|
|
170
|
+
timezone,
|
|
171
|
+
location: event.location,
|
|
172
|
+
locationType: event.locationType ?? "physical",
|
|
173
|
+
virtualUrl: event.virtualUrl ?? "",
|
|
174
|
+
status: normalizeEventStatus(event.published, event.status),
|
|
175
|
+
organizer: event.organizer,
|
|
176
|
+
organizerId: event.organizerId,
|
|
177
|
+
externalUrl: event.externalUrl,
|
|
178
|
+
imageUrl: event.imageUrl,
|
|
179
|
+
imageMediaId: event.featuredMediaId ?? event.imageMediaId ?? "",
|
|
180
|
+
featuredMediaId: event.featuredMediaId ?? event.imageMediaId ?? undefined,
|
|
181
|
+
categories: event.categories.join(", "),
|
|
182
|
+
venueId: event.venueId ?? "",
|
|
183
|
+
published: event.published,
|
|
184
|
+
repeatFrequency: recurrence?.frequency ?? "none",
|
|
185
|
+
recurrenceUntil: recurrence?.until ?? "",
|
|
186
|
+
recurrenceInterval: recurrence?.interval ?? 1,
|
|
187
|
+
weeklyWeekdays: recurrence?.frequency === "weekly" ? recurrence.weekdays : undefined,
|
|
188
|
+
monthlyDayOfMonth: recurrence?.frequency === "monthly" && recurrence.pattern.type === "dayOfMonth" ? recurrence.pattern.dayOfMonth : Number(start.slice(8, 10)),
|
|
189
|
+
monthlyPattern:
|
|
190
|
+
recurrence?.frequency === "monthly" ? recurrence.pattern.type : "dayOfMonth",
|
|
191
|
+
missingDayBehavior:
|
|
192
|
+
recurrence?.frequency === "monthly" && recurrence.pattern.type === "dayOfMonth"
|
|
193
|
+
? recurrence.pattern.missingDayBehavior
|
|
194
|
+
: "skip",
|
|
195
|
+
monthlyWeekday:
|
|
196
|
+
recurrence?.frequency === "monthly" && recurrence.pattern.type === "weekdayOfMonth"
|
|
197
|
+
? recurrence.pattern.weekday
|
|
198
|
+
: weekdayForDate(start),
|
|
199
|
+
monthlyPosition:
|
|
200
|
+
recurrence?.frequency === "monthly" && recurrence.pattern.type === "weekdayOfMonth"
|
|
201
|
+
? recurrence.pattern.position
|
|
202
|
+
: start
|
|
203
|
+
? monthlyPositionForDate(start)
|
|
204
|
+
: 1,
|
|
205
|
+
exceptions: event.exceptions ?? [],
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export function duplicateEventDraft(event: EventRecord): EventDraft {
|
|
210
|
+
return {
|
|
211
|
+
...eventToDraft(event),
|
|
212
|
+
title: `Copy of ${event.title}`,
|
|
213
|
+
published: false,
|
|
214
|
+
status: "draft",
|
|
215
|
+
exceptions: [],
|
|
216
|
+
};
|
|
217
|
+
}
|