@vermeulen.solutions/eventual 0.18.1 → 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/README.md CHANGED
@@ -5,15 +5,17 @@
5
5
  # Eventual RSVP – Core
6
6
 
7
7
  <p align="center">
8
- <a href="https://github.com/Vermeulen-Solutions/eventual-emdash-sandbox/actions/workflows/ci.yml"><img src="https://github.com/Vermeulen-Solutions/eventual-emdash-sandbox/actions/workflows/ci.yml/badge.svg" alt="CI Status" /></a>
9
- <a href="https://github.com/Vermeulen-Solutions/eventual-emdash-sandbox/releases"><img src="https://img.shields.io/github/v/release/Vermeulen-Solutions/eventual-emdash-sandbox?color=176b57&label=GitHub%20download" alt="Latest GitHub source download" /></a>
10
- <a href="https://plugins.emdashcms.com/plugins/@vermeulen.solutions/eventual"><img src="https://img.shields.io/badge/EmDash_Registry-0.15.0-0b4d3d" alt="EmDash Plugin Registry" /></a>
8
+ <a href="https://github.com/Vermeulen-Solutions/eventual-rsvp-core/actions/workflows/ci.yml"><img src="https://github.com/Vermeulen-Solutions/eventual-rsvp-core/actions/workflows/ci.yml/badge.svg" alt="CI Status" /></a>
9
+ <a href="https://github.com/Vermeulen-Solutions/eventual-rsvp-core/releases"><img src="https://img.shields.io/github/v/release/Vermeulen-Solutions/eventual-rsvp-core?color=176b57&label=GitHub%20download" alt="Latest GitHub source download" /></a>
10
+ <a href="https://plugins.emdashcms.com/plugins/@vermeulen.solutions/eventual"><img src="https://img.shields.io/badge/EmDash_Registry-0.18.2-0b4d3d" alt="EmDash Plugin Registry" /></a>
11
11
  <a href="https://emdashcms.com"><img src="https://img.shields.io/badge/EmDash-1.2.x%20%7C%201.4.x-0b4d3d" alt="EmDash Compatibility" /></a>
12
12
  <a href="./LICENSE"><img src="https://img.shields.io/badge/License-MIT-d89521" alt="License: MIT" /></a>
13
13
  <img src="https://img.shields.io/badge/TypeScript-strict-3178c6" alt="TypeScript Strict" />
14
14
  <img src="https://img.shields.io/badge/Sandbox-1%20host%20(language%20packs)-2ea44f" alt="One outbound host: language packs" />
15
15
  </p>
16
16
 
17
+ **Website:** [eventual.rsvp](https://eventual.rsvp/): documentation, install guide and support for Eventual RSVP – Core, Registrations and Tickets.
18
+
17
19
  Plan and publish events in [EmDash CMS](https://emdashcms.com). Write announcements, choose venues and organizers, set repeat schedules, and share events through your website and calendar subscriptions.
18
20
 
19
21
  **Current Registry release: 0.15.0.** Events are edited in EmDash's own collections, with rich text, images, drafts and translations. Your site builder connects the feeds to visitor pages; the screenshots below show the optional Astro showcase.
package/dist/index.mjs CHANGED
@@ -7,7 +7,7 @@
7
7
  /** @type {import("emdash").PluginDescriptor} */
8
8
  const descriptor = Object.freeze({
9
9
  "id": "eventual",
10
- "version": "0.18.1",
10
+ "version": "0.18.2",
11
11
  "format": "standard",
12
12
  "entrypoint": "@vermeulen.solutions/eventual/sandbox",
13
13
  "capabilities": [
package/dist/plugin.mjs CHANGED
@@ -8,6 +8,6 @@ function e(e={}){let t=[];return new Headers(e.headers).forEach((e,n)=>t.push([n
8
8
  `).split(`
9
9
  `)){if(/^\s*\x60\x60\x60/.test(t)){i(),a=!a,r(t);continue}if(a){r(t);continue}if(!t.trim()){i();continue}let e=/^(#{1,6})\s+(.+)$/.exec(t),o=/^(\s*)(?:([-*+])|\d+\.)\s+(.+)$/.exec(t),s=/^>\s?(.*)$/.exec(t);e?(i(),r(e[2],`h`+e[1].length)):o?(i(),r(o[3],`normal`,o[2]?`bullet`:`number`,Math.floor(o[1].length/2)+1)):s?(i(),r(s[1],`blockquote`)):n.push(we(t))}return i(),t}function Ee(e,t){return t.venueId?e?.get(t.venueId+`|`+(t.locale??``).toLowerCase())??e?.get(t.venueId):void 0}function De(e){if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=e,n=t.data&&typeof t.data==`object`?t.data:t,r=a(t.type?t.id:n.id??t.id??t._id??``);if(!r)return null;let i=a(n.name??n.title??t.name??t.title??``).trim(),o=a(n.street??n.address??n.streetAddress??t.street??t.address??t.streetAddress??``).trim(),s=a(n.street2??t.street2??``).trim(),c=a(n.locality??n.city??t.locality??t.city??``).trim(),l=a(n.region??n.state??t.region??t.state??``).trim(),u=a(n.postal_code??n.postalCode??n.zip??t.postal_code??t.postalCode??t.zip??``).trim(),d=a(n.country??t.country??``).trim(),f=N(n.directions??t.directions)||void 0,p=[[o,s].filter(Boolean).join(` `),[u,c].filter(Boolean).join(` `),l,d].filter(Boolean).join(`, `);return{id:r,name:i||p||`Event Venue`,address:p,street:o||void 0,street2:s||void 0,locality:c||void 0,region:l||void 0,postalCode:u||void 0,country:d||void 0,directions:f}}function Oe(e,t=``){let n=e.title||`Event`,r=E(e.virtualUrl??``),i=[e.description||``,r].filter(Boolean).join(`
10
10
 
11
- `),a=e.location||``;e.locationType===`virtual`?a=r||a:e.locationType===`hybrid`&&r&&a&&(a=`${a} · ${r}`);let o,s,c,l=``;if(e.allDay){let t=e.start.slice(0,10).replace(/-/g,``),n=new Date(e.end.slice(0,10)+`T00:00:00Z`);n.setUTCDate(n.getUTCDate()+1),o=`${t}/${n.toISOString().slice(0,10).replace(/-/g,``)}`,s=e.start.slice(0,10),c=n.toISOString().slice(0,10),l=`&allday=true`}else{let t=new Date(e.start).toISOString(),n=new Date(e.end).toISOString();o=`${t.replace(/[-:]/g,``).replace(/\.\d{3}/,``)}/${n.replace(/[-:]/g,``).replace(/\.\d{3}/,``)}`,s=t,c=n}let u=encodeURIComponent,d=`https://calendar.google.com/calendar/render?action=TEMPLATE&text=${u(n)}&dates=${o}&details=${u(i)}&location=${u(a)}`,f=`path=/calendar/action/compose&rru=addevent&subject=${u(n)}&body=${u(i)}&location=${u(a)}&startdt=${u(s)}&enddt=${u(c)}${l}`,p=`https://outlook.live.com/calendar/0/deeplink/compose?${f}`,m=`https://outlook.office.com/calendar/0/deeplink/compose?${f}`,h=e.id.split(`#`)[0],g=`/_emdash/api/plugins/eventual/calendar?eventId=${u(h)}`;return{google:d,outlook:p,office365:m,ics:t?new URL(g,t).href:g}}function ke(e,t){if(typeof e!=`string`||!e.trim())return``;try{let n=t?new URL(e,t):new URL(e);return n.protocol===`http:`||n.protocol===`https:`?n.href:``}catch{return``}}function Ae(e){let t=ke(e.virtualUrl??``);return e.locationType===`virtual`?t||e.location:e.locationType===`hybrid`?[e.location,t].filter(Boolean).join(` · `):e.location}function je(e){return ke(e.externalUrl)||(e.locationType===`virtual`||e.locationType===`hybrid`?ke(e.virtualUrl??``):``)}function Me(e){return e.status===`cancelled`?`CANCELLED`:e.status===`postponed`?`TENTATIVE`:`CONFIRMED`}function Ne(e){if(typeof e!=`string`||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,3})?)?(?:Z|[+-]\d{2}:\d{2})$/.test(e))return!1;let t=e.slice(11,19).split(`:`);return p(e.slice(0,10))&&Number.isFinite(Date.parse(e))&&Number(t[0])<=23&&Number(t[1])<=59&&(!t[2]||Number(t[2])<=59)}function P(e){if(typeof e!=`string`)return e??void 0;if(e.trim())try{return JSON.parse(e)}catch{i(`Invalid JSON.`)}}const Pe=[`start`,`end`,`start_date`,`end_date`,`all_day`,`timezone`,`recurrence`,`exceptions`,`occurrence_content`,`venue`,`venue_id`,`organizer_ref`,`organizer_id`,`location_type`,`event_status`,`calendar_uid`,`legacy_id`,`categories`,`virtual_url`,`external_url`,`image_url`,`organizer_details`,`previous_start_date`,`schedule_history`];function Fe(e,t={}){let n={...e},r=e.all_day??e.allDay??!1,a=r===0?!1:r===1?!0:r;typeof a!=`boolean`&&i(`all_day must be a boolean.`);let o=e.timezone??`Europe/Zurich`;(typeof o!=`string`||!h(o))&&i(`Invalid IANA timezone.`);let s=a?e.start_date??e.start:e.start,c=a?e.end_date??e.end:e.end;(typeof s!=`string`||typeof c!=`string`||!s||!c)&&i(`Start and end are required.`);let l=s,u=c;if(a)(e.start_date!=null&&!p(l)||e.end_date!=null&&!p(u))&&i(`All-day date fields must use YYYY-MM-DD.`),[l,u].some(e=>!p(e)&&!Ne(e))&&i(`Invalid all-day date representation.`),l=l.slice(0,10),u=u.slice(0,10),(!p(l)||!p(u)||u<l)&&i(`Invalid inclusive all-day dates.`),n.start_date=l,n.end_date=u,delete n.start,delete n.end;else{let e=e=>{if(Ne(e))return new Date(e).toISOString()},t=e(l),r=e(u);if(t&&r)l=t,u=r;else{let e=y({start:l,end:u,allDay:!1,timezone:o});e.dates||i(`Invalid local datetime or timezone.`),{start:l,end:u}=e.dates}Date.parse(u)<Date.parse(l)&&i(`End must be at or after start.`),n.start=l,n.end=u,delete n.start_date,delete n.end_date}let d=P(e.recurrence);if(d!=null&&!O(d)&&i(`Invalid recurrence rule.`),d&&O(d)){let e=a?l:_(l,o)?.slice(0,10);(!e||d.until<e)&&i(`Recurrence until precedes start.`),!a&&(new Date(l).getUTCSeconds()||new Date(l).getUTCMilliseconds())&&i(`Recurring starts require minute precision.`)}let f=P(e.exceptions)??[];(!Array.isArray(f)||f.length>500)&&i(`Exceptions must be an array of at most 500 items.`);let m=new Set([`start`,`end`,`allDay`,`timezone`,`locationType`,`virtualUrl`,`status`,`externalUrl`,`imageUrl`,`imageMediaId`,`categories`]),g={id:`validation`,start:l,end:u,allDay:a,timezone:o,recurrence:d,exceptions:f,published:!0};for(let e of f)if((!e||typeof e!=`object`||typeof e.recurrenceId!=`string`||![`cancelled`,`modified`].includes(e.status))&&i(`Invalid exception.`),e.status===`modified`){(!e.overrides||typeof e.overrides!=`object`||Array.isArray(e.overrides)||!Object.keys(e.overrides).length)&&i(`Modified exceptions require overrides.`),Object.keys(e.overrides).some(e=>!m.has(e))&&i(`Editorial exception overrides belong in occurrence_content.`);let t=j(g,e.recurrenceId);t||i(`Exception is not a scheduled occurrence.`);let n={...t,...e.overrides};(typeof n.allDay!=`boolean`||!h(n.timezone))&&i(`Invalid exception timezone or allDay.`),(n.allDay?!p(n.start)||!p(n.end)||n.end<n.start:!Number.isFinite(Date.parse(n.start))||!Number.isFinite(Date.parse(n.end))||Date.parse(n.end)<Date.parse(n.start))&&i(`Invalid exception schedule.`),!n.allDay&&[n.start,n.end].some(e=>!Ne(e))&&i(`Timed exceptions require ISO instants.`);for(let t of[`locationType`,`virtualUrl`,`status`,`externalUrl`,`imageUrl`,`imageMediaId`])t in e.overrides&&typeof e.overrides[t]!=`string`&&i(`Exception field must be text: `+t);e.overrides.locationType!==void 0&&![`physical`,`virtual`,`hybrid`].includes(e.overrides.locationType)&&i(`Invalid exception location type.`),e.overrides.status!==void 0&&![`published`,`cancelled`,`postponed`,`rescheduled`].includes(e.overrides.status)&&i(`Invalid exception status.`);for(let t of[`virtualUrl`,`externalUrl`,`imageUrl`])e.overrides[t]&&!ke(e.overrides[t])&&i(`Exception URLs must use HTTP(S).`);e.overrides.categories!==void 0&&(!Array.isArray(e.overrides.categories)||e.overrides.categories.some(e=>typeof e!=`string`))&&i(`Exception categories must be an array of strings.`)}f.length&&(!d||!Ce(g))&&i(`Duplicate or invalid exception recurrence IDs.`);let v=P(e.occurrence_content)??[];(!Array.isArray(v)||v.length>500||v.some(e=>!e||typeof e.recurrenceId!=`string`||!e.overrides||Object.keys(e.overrides).some(e=>![`title`,`description`,`location`,`organizer`].includes(e))))&&i(`Invalid occurrence_content.`),(new Set(v.map(e=>e.recurrenceId)).size!==v.length||!t.allowStaleOccurrenceCopy&&v.some(e=>!d||!j(g,e.recurrenceId)))&&i(`Invalid editorial recurrence IDs.`);for(let e of v)for(let[t,n]of Object.entries(e.overrides))(t===`description`?typeof n!=`string`&&!Array.isArray(n):typeof n!=`string`)&&i(`Invalid occurrence copy field: `+t);e.location_type!=null&&![`physical`,`virtual`,`hybrid`].includes(String(e.location_type))&&i(`Invalid location type.`),e.event_status!=null&&![`published`,`cancelled`,`postponed`,`rescheduled`].includes(String(e.event_status))&&i(`Invalid event status.`);for(let t of[`virtual_url`,`external_url`,`image_url`])e[t]&&(typeof e[t]!=`string`||!ke(e[t]))&&i(`Public URLs must use HTTP(S): `+t);let b=P(e.organizer_details);b!=null&&(typeof b!=`object`||Array.isArray(b)||[`id`,`name`,`website`,`contactUrl`].some(e=>typeof b[e]!=`string`)||[`website`,`contactUrl`].some(e=>{let t=b[e];return t&&!ke(t)}))&&i(`Invalid organizer details.`),e.previous_start_date&&!p(e.previous_start_date)&&!Ne(e.previous_start_date)&&i(`Invalid previous start date.`);let x=P(e.schedule_history);return x!=null&&(!Array.isArray(x)||x.length>10||x.some(e=>!e||!Ne(e.changedAt)||!h(e.timezone)||typeof e.allDay!=`boolean`||(e.allDay?!p(e.start)||!p(e.end)||e.end<e.start:!Ne(e.start)||!Ne(e.end)||Date.parse(e.end)<Date.parse(e.start))))&&i(`Invalid schedule history.`),n.all_day=a,n.timezone=o,S(e.categories),e.calendar_uid!=null&&(typeof e.calendar_uid!=`string`||!/^[A-Za-z0-9.!~*'()%_-]+@[A-Za-z0-9.-]+$/.test(e.calendar_uid))&&i(`Invalid calendar UID.`),n}const Ie=new Set([`image/avif`,`image/gif`,`image/jpeg`,`image/png`,`image/webp`]),Le=8*1024*1024;function Re(e){return Ie.has(e.toLowerCase())}function ze(e,t){let n=new URLSearchParams({eventId:t});return`/_emdash/api/plugins/${encodeURIComponent(e)}/publicEventImage?${n}`}function Be(e,t,n=`eventual`,r){let i=w(t,e.location);return{...e.locale?{locale:e.locale}:{},...e.translationGroup?{translationGroup:e.translationGroup}:{},id:e.id,updatedAt:e.updatedAt,title:e.title,description:e.description,...e.descriptionBlocks?{descriptionBlocks:e.descriptionBlocks}:{},start:e.start,end:e.end,allDay:e.allDay,timezone:e.timezone,location:i,locationType:e.locationType??`physical`,...E(e.virtualUrl??``)?{virtualUrl:E(e.virtualUrl??``)}:{},status:ce(e.published,e.status),organizer:r?.name??(e.organizer||e.organizerDetails?.name||``),...r?{organizerDetails:{id:r.id,name:r.name,website:E(r.website),contactUrl:E(r.contactUrl)}}:e.organizerDetails?{organizerDetails:e.organizerDetails}:{},...e.status===`rescheduled`&&e.previousStartDate?{previousStartDate:e.previousStartDate}:{},externalUrl:e.externalUrl,imageUrl:e.featuredMediaId||e.imageMediaId?e.imageUrl?.includes(`publicEventImage`)?e.imageUrl:ze(n,e.id):e.imageUrl||``,...e.imageMedia?{imageMedia:e.imageMedia}:{},categories:b(e.categories),venue:t?{id:t.id,name:t.name,address:C(t),addressParts:{street:t.street,street2:t.street2,locality:t.locality,region:t.region,postalCode:t.postalCode,country:t.country}}:null,directionsUrl:T(i),calendarLinks:Oe({id:e.id,title:e.title,description:e.description,start:e.start,end:e.end,allDay:e.allDay,timezone:e.timezone,location:i,locationType:e.locationType,virtualUrl:e.virtualUrl})}}const Ve=e=>e instanceof Date?e.toISOString():a(e);function He(e){if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=e,n=!!t.data&&typeof t.data==`object`&&!Array.isArray(t.data),r=n?t.data:t,i=a(n&&t.type?t.id:r.id??t.id);if(!i)return null;try{let e=P(r.exceptions)??[];if(!Array.isArray(e))return null;let o=Object.hasOwn(r,`all_day`)||n&&(typeof t.type==`string`||!Object.hasOwn(r,`published`)),s=o?e:e.map(e=>({...e,overrides:e.overrides?Object.fromEntries(Object.entries(e.overrides).filter(([e])=>![`title`,`description`,`location`,`organizer`,`locale`].includes(e))):void 0})).filter(e=>e.status===`cancelled`||Object.keys(e.overrides??{}).length),c=Fe({...r,all_day:r.all_day??r.allDay,exceptions:s},{allowStaleOccurrenceCopy:!0}),l=c.all_day,u=a(l?c.start_date:c.start),d=a(l?c.end_date:c.end),f=P(r.recurrence),p=e.map(e=>({...e,overrides:e.overrides?{...e.overrides}:void 0})),m=P(r.occurrence_content)??[];for(let e of m){if(!f||!j({id:i,start:u,end:d,allDay:l,timezone:a(c.timezone),recurrence:f},e.recurrenceId))continue;let t=p.find(t=>t.recurrenceId===e.recurrenceId);t?.status!==`cancelled`&&(t?t.overrides={...t.overrides,...e.overrides}:p.push({recurrenceId:e.recurrenceId,status:`modified`,overrides:e.overrides}))}let h=o?n&&typeof t.status==`string`?t.status:r.status:void 0,g=h?h===`published`:r.published===!0,_=r.event_status??([`cancelled`,`postponed`,`rescheduled`].includes(a(r.status))?r.status:g?`published`:`draft`),v=typeof r.featured_image==`string`?P(r.featured_image):r.featured_image,y=Object.hasOwn(r,`venue_id`)?r.venue_id:r.venue??r.venueId,b=typeof y==`string`?y:y&&typeof y==`object`?a(y.id):``,x=S(r.categories),C=a(v?.id??r.featuredMediaId??r.featured_media_id??r.imageMediaId),w=v?.meta?.storageKey,T=a(v?.src||v?.url)||(w?`/_emdash/api/media/file/`+encodeURIComponent(String(w)):``),E=e=>typeof e==`number`&&e>0?e:void 0,D=T?{src:T,width:E(v?.width),height:E(v?.height),alt:a(v?.alt)||void 0}:void 0;return{id:i,title:a(r.title).trim(),description:typeof r.description==`string`?r.description:JSON.stringify(r.description??[]),descriptionBlocks:Array.isArray(r.description)?r.description:void 0,start:u,end:d,allDay:l,timezone:a(c.timezone),published:g,status:_,recurrence:f,exceptions:p,location:a(r.location),locationType:r.location_type??r.locationType??`physical`,virtualUrl:a(r.virtual_url??r.virtualUrl),externalUrl:a(r.external_url??r.externalUrl),organizer:a(r.organizer),organizerId:a(Object.hasOwn(r,`organizer_id`)?r.organizer_id:typeof r.organizer_ref==`object`?r.organizer_ref?.id:r.organizer_ref??r.organizerId),organizerDetails:P(r.organizer_details),venueId:b,imageUrl:C?``:a(r.image_url??r.imageUrl??v?.src??v?.url),imageMediaId:C,featuredMediaId:C||void 0,imageMedia:D,categories:x,createdAt:Ve(t.createdAt??r.created_at??r.createdAt)||`1970-01-01T00:00:00.000Z`,updatedAt:Ve(t.updatedAt??r.updated_at??r.updatedAt)||`1970-01-01T00:00:00.000Z`,locale:a(t.locale??r.locale)||void 0,translationGroup:a(t.translationGroup??r.translation_group??r.translationGroup??t.translation_group)||void 0,calendarUid:a(r.calendar_uid??r.calendarUid)||void 0,calendarSequence:typeof r.calendarSequence==`number`?r.calendarSequence:void 0,previousStartDate:a(r.previous_start_date??r.previousStartDate)||void 0,scheduleHistory:P(r.schedule_history??r.scheduleHistory),slug:a(t.slug??r.slug)||void 0,publicUrl:a(t.publicUrl??t.url??r.publicUrl??r.url)||void 0}}catch{return null}}function Ue(e,t,n,r=`eventual`){let i=Ee(t,e),a=Be(e,i?{...i,street:i.street??``,street2:i.street2??``,locality:i.locality??``,region:i.region??``,postalCode:i.postalCode??``,country:i.country??``,createdAt:``,updatedAt:``}:void 0,r),o=a.imageUrl||e.imageUrl;if(n&&o)try{o=new URL(o,n).href}catch{o=``}let s=e.imageMedia,c=s?{...s,src:n&&s.src.startsWith(`/`)?new URL(s.src,n).href:s.src}:void 0;return{...a,description:N(e.description),...e.descriptionBlocks?{descriptionBlocks:e.descriptionBlocks}:{},imageUrl:o,...c?{imageMedia:c}:{},organizerDetails:e.organizerDetails,previousStartDate:e.previousStartDate,locale:e.locale,translationGroup:e.translationGroup,slug:e.slug,publicUrl:e.publicUrl}}const We=new WeakMap;function Ge(e,t,n){let r=We.get(e);return r||We.set(e,r=Object.create(null)),r[t]??=Promise.resolve().then(n)}function Ke(e,t){let n=We.get(e);n&&delete n[t]}const qe=`collections`,Je=`legacyReads`,Ye=/^[a-z][a-z0-9_]{0,62}$/;async function Xe(e){return(await Ze(e))?.events??`events`}function Ze(e){return Ge(e,`collection-settings`,async()=>await e.settings?.get(qe)??void 0)}function Qe(e){return Ge(e,`legacy-reads`,async()=>await e.settings?.get(Je)===!0)}async function $e(e,t){await e.settings.set(Je,t),Ke(e,`legacy-reads`)}function F(e){return Ge(e,`schemas`,async()=>await e.schema?.listCollections()??[])}function et(e){return Ge(e,`bindings`,()=>tt(e))}async function tt(e){let[t,n]=await Promise.all([Ze(e),F(e)]);t&&(!t.events||Object.values(t).some(e=>typeof e!=`string`||e!==``&&!Ye.test(e)))&&i(`Invalid collections. Choose them again in Event settings.`);let r=t?.events??`events`,a=n.find(e=>e.slug===r);t&&!a&&i(`The selected event collection is missing.`);let o=(e,t)=>{let n=a?.fields?.find(t=>t.slug===e);return String(n?.validation?.targetCollection??n?.options?.collection??t)},s={events:r,venues:t?.venues??o(`venue`,`venues`),organizers:t?.organizers??o(`organizer_ref`,`organizers`)};if(t)for(let e of[s.venues,s.organizers])e&&!n.some(t=>t.slug===e)&&i(`Selected directory missing. Review Event settings.`);return{...s,schema:a,schemas:n,configured:!!t}}async function nt(e,t){(!t.events||Object.values(t).some(e=>typeof e!=`string`||e!==``&&!Ye.test(e)))&&i(`Choose valid collection names.`);let n=await F(e),r=n.find(e=>e.slug===t.events);r||i(`Choose an existing event collection.`);for(let[e,t]of Object.entries({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`})){let n=r.fields.find(t=>t.slug===e);(!n||n.type!==t)&&i(`Event collection needs `+e+` (`+t+`). Apply the event blueprint first.`);let a=[`title`,`description`,`occurrence_content`].includes(e);n.translatable!==a&&i(`Set `+e+` translatable to `+a+` before selecting this collection.`)}for(let[e,a]of[[`venues`,`venue`],[`organizers`,`organizer_ref`]]){let o=t[e],s=n.find(e=>e.slug===o);o&&(!s||!s.fields.some(e=>[`name`,`title`].includes(e.slug)&&e.type===`string`))&&i(`Choose a `+e+` collection with a name or title field.`);let c=r.fields.find(e=>e.slug===a),l=r.fields.find(t=>t.slug===(c?.validation?.relation?e===`venues`?`venue_id`:`organizer_id`:a)),u=l?.validation?.targetCollection??l?.options?.collection;o&&(l?.type!==`reference`||u!==o)&&i(`Set the event `+a+` reference target to `+o+` first.`),!o&&l&&i(`This event schema has a `+a+` reference. Select its target collection.`),l?.translatable!==void 0&&l.translatable!==!1&&i(`Event references must be shared across languages.`)}await e.settings.set(qe,t),Ke(e,`collection-settings`),Ke(e,`bindings`)}function rt(e){if(typeof e==`string`)return e.trim()||void 0;if(e&&typeof e==`object`&&!Array.isArray(e))return rt(e.id)}function I(e,t){let n=e?.fields.find(e=>e.slug===t),r=n?.validation?.targetCollection??n?.options?.collection;return typeof r==`string`&&r?r:t===`venue`?`venues`:`organizers`}function it(e,t){return(e?.fields.find(e=>e.slug===t))?.validation?.relation?t===`venue`?`venue_id`:`organizer_id`:t}async function L(e){return(await et(e)).schema}var at=class extends Error{constructor(){super(`The sandbox RPC budget is exceeded.`),this.name=`SandboxBudgetError`}};const ot=Symbol(`eventual invocation budget`),st=new WeakMap;function R(e){if(e[ot])return e;let t=st.get(e);if(t)return t;let n={used:0,reserved:0},r={...e,[ot]:n},i=e=>new Proxy(e,{get(e,t){let r=Reflect.get(e,t,e);return typeof r==`function`?(...t)=>{if(n.used+n.reserved>=10)throw new at;return n.used++,Reflect.apply(r,e,t)}:r}});for(let[t,n]of Object.entries(e))![`site`,`plugin`,`storage`].includes(t)&&n&&typeof n==`object`&&(r[t]=i(n));return e.storage&&(r.storage=new Proxy(e.storage,{get(e,t){let n=Reflect.get(e,t,e);return n&&typeof n==`object`?i(n):n}})),st.set(e,r),r}function ct(e,t){let n=e[ot];if(!n)return()=>{};if(n.used+n.reserved+t>10)throw new at;n.reserved+=t;let r=!1;return()=>{r||=(n.reserved-=t,!0)}}function lt(e){let t=e[ot];return t?10-t.used-t.reserved:10}function ut(e,t){if(!e)return{...t,calendarSequence:t.calendarSequence??Math.floor(Date.now()/1e3)};let n=Math.max(e.calendarSequence??(Math.floor(Date.parse(e.updatedAt)/1e3)||0),t.calendarSequence??0)+1;n>2147483647&&i(`Calendar sequence exhausted.`);let r=e.start!==t.start||e.end!==t.end||e.allDay!==t.allDay||e.timezone!==t.timezone,a=r?[{start:e.start,end:e.end,allDay:e.allDay,timezone:e.timezone,changedAt:t.updatedAt},...e.scheduleHistory??[]].slice(0,10):e.scheduleHistory;return{...t,calendarSequence:n,...a?{scheduleHistory:a}:{},...r?{previousStartDate:e.start}:e.previousStartDate?{previousStartDate:e.previousStartDate}:{}}}const dt=1e4;var ft=class extends Error{constructor(e){super(`More than ${e} events matched the request. Narrow the query or contact the site administrator.`),this.limit=e,this.name=`EventScanLimitError`}};function pt(e){return e.storage.events}function mt(e){return e.storage.venues}function ht(e){return e.storage.calendar_cancellations}function z(e,t){return pt(e).get(t)}function gt(e,t){return vt(e,t)}function _t(e){return new Date(Math.max(Date.now(),Date.parse(e??``)+1||0)).toISOString()}async function vt(e,t){let n=await pt(e).get(t.id);t=ut(n,t);let r=await bt(e,n,t);await pt(e).put(t.id,t);for(let t=0;t<r.length;t+=100)await ht(e).deleteMany(r.slice(t,t+100));return t}async function yt(e,t){return await bt(e,await pt(e).get(t),null),pt(e).delete(t)}async function bt(e,t,n){let r=new Date().toISOString().slice(0,10),i=new Date(`${r}T00:00:00Z`);i.setUTCDate(i.getUTCDate()+365);let a=i.toISOString().slice(0,10),o=t?.published?M([t],r,a):[],s=n?.published?M([n],r,a):[],c=new Set(s.map(e=>e.id)),l=(e,t)=>`locale:`+e.toLowerCase()+`:`+t,u=[...c,...s.flatMap(e=>Object.keys(n?.translations??{}).map(t=>l(t,e.id)))],d=o.filter(e=>!c.has(e.id)),f=Object.keys(t?.translations??{}).filter(e=>!Object.hasOwn(n?.translations??{},e)),p=n?o.flatMap(e=>f.map(t=>({item:e,locale:t}))):[],m=new Date().toISOString(),h=p.map(({item:e,locale:r})=>({id:l(r,e.id),data:{id:e.id,eventId:t.id,start:e.start,end:e.end,allDay:e.allDay,timezone:e.timezone,cancelledAt:m,locale:r.toLowerCase(),categories:e.categories,calendarUid:t.calendarUid,translationGroup:t.translationGroup,calendarSequence:n?.calendarSequence}}));return d.length&&h.push(...d.map(e=>({id:e.id,data:{id:e.id,eventId:t.id,start:e.start,end:e.end,allDay:e.allDay,timezone:e.timezone,cancelledAt:m,translationGroup:e.translationGroup??t.translationGroup,calendarUid:t.calendarUid,calendarSequence:n?.calendarSequence??(t.calendarSequence??Math.floor(Date.parse(t.updatedAt)/1e3))+1,categories:e.categories,locales:e.locale?[e.locale.toLowerCase(),...Object.keys(t.translations??{}).map(e=>e.toLowerCase())]:void 0}}))),h.length&&await ht(e).putMany(h),u}async function xt(e){let t=[],n;do{let r=await ht(e).query({limit:100,cursor:n});if(t.push(...r.items.map(e=>e.data)),r.hasMore&&(!r.cursor||r.cursor===n)&&i(`Incomplete cancellation cursor.`),t.length>dt)throw new ft(dt);n=r.hasMore?r.cursor:void 0}while(n);return t}function St(e,t){return mt(e).get(t)}function Ct(e,t){return mt(e).put(t.id,t)}function wt(e,t){return mt(e).delete(t)}async function Tt(e,t){return await pt(e).count({venueId:t})>0}async function Et(e,t={}){let n=[],r=t.maxItems??dt;if(!Number.isInteger(r)||r<1||r>dt)throw RangeError(`maxItems must be between 1 and ${dt}`);let a,o=t.through?new Date(Date.parse(`${t.through}T00:00:00Z`)+2*864e5).toISOString().slice(0,10):void 0,s=new Set;do{let c=await pt(e).query({where:{...t.published===void 0?{}:{published:t.published},...o?{start:{lt:o}}:{}},orderBy:{start:t.order??`asc`},limit:Math.min(100,r-n.length),cursor:a});if(n.push(...c.items.map(e=>e.data)),c.hasMore&&!c.cursor&&i(`Event storage returned an incomplete page without a cursor.`),c.hasMore&&s.has(c.cursor)&&i(`Event storage returned a repeated cursor.`),c.cursor&&s.add(c.cursor),a=c.hasMore?c.cursor:void 0,a&&n.length>=r)throw new ft(r)}while(a);return n}async function Dt(e){let t=[],n;do{let r=await mt(e).query({orderBy:{name:`asc`},limit:100,cursor:n});if(t.push(...r.items.map(e=>e.data)),r.hasMore&&(!r.cursor||r.cursor===n)&&i(`Incomplete venue cursor.`),t.length>5e3)throw new ft(5e3);n=r.hasMore?r.cursor:void 0}while(n);return t}async function Ot(e,t){return t.length?mt(e).getMany([...new Set(t)]):new Map}function kt(e){return e.storage.organizers}async function At(e){let t=[],n;do{let r=await kt(e).query({orderBy:{name:`asc`},limit:100,cursor:n});t.push(...r.items.map(e=>e.data)),r.hasMore&&(!r.cursor||t.length>=5e3)&&i(`Organizer list exceeds the supported scan limit or has an incomplete page.`),n=r.hasMore?r.cursor:void 0}while(n);return t}function jt(e,t){return t.length?kt(e).getMany([...new Set(t)]):Promise.resolve(new Map)}async function B(e){if(!e.schema||!e.content)return;let t=await L(e);return t&&!t.fields?.some(e=>e.slug===`start`)&&i(`Not an event schema.`),t}async function V(e,t,n=!1){let r=[],a,o=new Set;do{let s=await e.content.list(t,{limit:100,cursor:a,...n?{where:{status:`published`}}:{}});if(r.push(...s.items),r.length>dt)throw new ft(dt);if(!s.hasMore)break;(!s.cursor||o.has(s.cursor))&&i(`Invalid cursor.`),o.add(s.cursor),a=s.cursor}while(!0);return r}async function Mt(e,t){let n=await B(e);if(!n)return await Qe(e)||i(`Events are not connected to a content type. Turn on "Show old events saved inside the plugin".`),{native:!1,events:(await Et(e,{published:!0,...t?{through:t}:{}})).map(t=>t.locale?t:{...t,locale:e.site?.locale??`en`}),schema:n};let r=await V(e,n.slug,!0),a=[];for(let e of r){let t=He(e);t||i(`Invalid event: `+e.id),t.published&&a.push(t)}return{native:!0,events:a,schema:n}}async function Nt(e,t,n){let r=new Map,i=[...new Set(t.flatMap(e=>e.venueId?[e.venueId]:[]))],a=n?await Pt(e,I(n,`venue`),t,e=>e.venueId):await Ot(e,i);for(let[e,t]of a){let n=De(t);n&&r.set(e,n)}return r}async function Pt(e,t,n,r){let i=new Map;for(let e of n){let t=r(e);if(!t)continue;let n=i.get(t)??new Set;n.add((e.locale??``).toLowerCase()),i.set(t,n)}let a=new Map;if(!i.size||!e.content)return a;let o=await Ge(e,`directory:`+t,()=>V(e,t,!0)),s=new Map,c=new Map;for(let e of o){if(e.status!==`published`)continue;s.set(e.id,e);let t=e.translationGroup||e.id,n=(e.locale??``).toLowerCase();c.set(`${t}|${n}`,e)}for(let[e,t]of i){let n=s.get(e);if(n){a.set(e,n);for(let r of t){if(!r||r===(n.locale??``).toLowerCase())continue;let t=n.translationGroup||n.id,i=c.get(`${t}|${r}`);i&&a.set(`${e}|${r}`,i)}}}return a}function Ft(e,t,n=!1){let r=e=>Intl.getCanonicalLocales(e)[0].toLowerCase(),i=t?r(t):void 0,a=new Map;for(let t of e){let e=t.translationGroup??t.id,n=a.get(e)??[];n.push(t);for(let[e,r]of Object.entries(t.translations??{}))n.push({...t,...r,locale:e,descriptionBlocks:void 0,exceptions:t.exceptions.map(e=>({...e,overrides:e.overrides?Object.fromEntries(Object.entries(e.overrides).filter(([e])=>![`title`,`description`,`location`,`organizer`,`locale`].includes(e))):void 0}))});a.set(e,n)}let o=[];for(let t of a.values()){t.sort((e,t)=>(e.locale??``).localeCompare(t.locale??``)||e.id.localeCompare(t.id));let a=i?t.find(e=>e.locale&&r(e.locale)===i):t.find(t=>!t.translations||e.includes(t))??t[0];if(a)o.push(a);else if(!n){let n=t.find(t=>e.includes(t))??t[0],r=n.locale?`[`+n.locale.toUpperCase()+`] `:``;o.push({...n,title:r+n.title,exceptions:(n.exceptions??[]).map(e=>e.overrides?.title===void 0?e:{...e,overrides:{...e.overrides,title:r+e.overrides.title}})})}}return o}async function It(e,t,n=!0){let r=new Map,i=await L(e);if(t.some(e=>e.organizerId)){let n=I(i,`organizer_ref`);for(let[i,a]of await Pt(e,n,t,e=>e.organizerId))r.set(i,{id:a.id,name:String(a.data.name??a.data.title??``),website:E(String(a.data.website??``)),contactUrl:E(String(a.data.contact_url??a.data.contactUrl??``))})}let a=e.plugin?.id??`eventual`,o=new Map,s={};if(n&&i&&e.content?.getPublicUrl)for(let n of t){let t=n.id.split(`#`)[0],r=s[n.locale];if(!n.published||!n.slug||o.has(t))continue;let a=(i.urlPattern??`/`+i.slug+`/{slug}`).replace(`{slug}`,encodeURIComponent(n.slug)).replace(`{id}`,t).replace(/(.)\/$/,`$1`);if(r){o.set(t,r[0]+a+r[1]);continue}if(lt(e)<3)continue;let c=await Ge(e,`url:`+i.slug+`:`+t,()=>e.content.getPublicUrl(i.slug,t)),l=c?.replace(/\/$/,``);o.set(t,c),l?.endsWith(a)&&!a.includes(`{`)&&(s[n.locale]=[l.slice(0,-a.length),c.slice(l.length)])}return Promise.all(t.map(async e=>{let t=r.get((e.organizerId??``)+`|`+(e.locale??``).toLowerCase())??r.get(e.organizerId??``),n=o.get(e.id.split(`#`)[0])??e.publicUrl;return{...e,organizer:e.organizer||t?.name||e.organizerDetails?.name||``,organizerDetails:t??e.organizerDetails,publicUrl:n,imageUrl:e.featuredMediaId||e.imageMediaId?ze(a,e.id):e.imageUrl||``}}))}function Lt(e){let t=e=>({rule:null,error:e}),n=String(e.frequency||``).trim().toLowerCase();if(!n||n===`none`)return{rule:null};let r=String(e.until||``).trim();if(!p(r))return t(`Repeat until must be a valid YYYY-MM-DD date.`);let i=e.interval===void 0||String(e.interval).trim()===``?1:Number(e.interval);if(!Number.isInteger(i)||i<1||i>52)return t(`Interval must be an integer between 1 and 52.`);let a={frequency:n,until:r,...i>1?{interval:i}:{}};if(n===`weekly`&&e.weekdays){let n=Array.isArray(e.weekdays)?e.weekdays:String(e.weekdays).split(`,`).map(e=>e.trim());if(n.some(e=>!D.includes(e)))return t(`Choose valid weekdays.`);n.length&&(a.weekdays=te(n))}else if(n===`monthly`){let n=e.monthlyPatternType??`dayOfMonth`;if(n===`dayOfMonth`){let r=Number(e.dayOfMonth??1);if(!Number.isInteger(r)||r<1||r>31)return t(`Day of month must be between 1 and 31.`);a.pattern={type:n,dayOfMonth:r,missingDayBehavior:e.missingDayBehavior===`lastDay`?`lastDay`:`skip`}}else if(n===`weekdayOfMonth`){let r=String(e.weekday||`monday`).toLowerCase();if(!D.includes(r))return t(`Choose a valid weekday.`);let i=e.position===`last`?`last`:Number(e.position??1);if(i!==`last`&&(!Number.isInteger(i)||i<1||i>5))return t(`Choose first, second, third, fourth, fifth or last.`);a.pattern={type:n,weekday:r,position:i}}else return t(`Choose a monthly pattern.`)}return[`daily`,`weekly`,`monthly`].includes(n)?O(a)?{rule:a}:t(`Invalid `+n+` recurrence.`):t(`Unsupported recurrence frequency: `+n)}function Rt(e){if(e=P(e),!O(e))return{frequency:`none`,interval:1};let t={frequency:e.frequency,interval:e.interval??1,until:e.until};return e.frequency===`weekly`&&e.weekdays&&(t.weekdays=[...e.weekdays]),e.frequency===`monthly`&&e.pattern&&(e.pattern.type===`dayOfMonth`?(t.monthlyPatternType=`dayOfMonth`,t.dayOfMonth=e.pattern.dayOfMonth,t.missingDayBehavior=e.pattern.missingDayBehavior):(t.monthlyPatternType=`weekdayOfMonth`,t.weekday=e.pattern.weekday,t.position=e.pattern.position)),t}function zt(e){if(e=P(e),!O(e))return`Does not repeat`;let t=ee(e);if(e.frequency===`monthly`){let n=e.pattern;t+=n.type===`dayOfMonth`?` on day ${n.dayOfMonth} (${n.missingDayBehavior===`skip`?`skip missing months`:`use last day if missing`})`:` on ${n.position===`last`?`last`:[`first`,`second`,`third`,`fourth`,`fifth`][n.position-1]} ${n.weekday[0].toUpperCase()}${n.weekday.slice(1)}`}return`${t} through ${e.until}`}function Bt(e){let t=new Set([`title`,`description`,`excerpt`,`featured_image`,`image_url`,`start`,`end`,`start_date`,`end_date`,`all_day`,`timezone`,`location_type`,`venue`,`venue_id`,`location`,`virtual_url`,`external_url`,`organizer`,`organizer_ref`,`organizer_id`,`organizer_details`,`categories`,`recurrence`]),n=structuredClone(Object.fromEntries(Object.entries(e).filter(([e])=>t.has(e))));return n.event_status=`published`,n}function Vt(e,t,n){return{version:1,dependencies:[...new Set([e.slug,I(e,`venue`),I(e,`organizer_ref`),`emdash:settings`])],generatedAt:new Date(t).toISOString(),expiresAt:new Date(Math.min(t+15e3,n?(Math.floor(t/864e5)+1)*864e5:1/0)).toISOString()}}function Ht(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function Ut(e,t){try{return await Wt(e,R(t))}catch(e){if(e instanceof at)return{ok:!1,error:`SANDBOX_BUDGET_EXCEEDED`,details:e.message,events:void 0};throw e}}async function Wt(e,t){let n={ok:!1,error:`INVALID_QUERY`};if(!Ht(e)||[`from`,`through`,`category`,`locale`,`eventId`].some(t=>e[t]!==void 0&&typeof e[t]!=`string`)||[e.strict,e.publicUrls].some(e=>![void 0,!0,!1,`true`,`false`].includes(e)))return n;try{e.locale&&Intl.getCanonicalLocales(e.locale)}catch{return n}let r=typeof e.eventId==`string`&&e.eventId.trim()?e.eventId.trim():void 0,i=Date.now(),a=new Date(i).toISOString().slice(0,10),o=e.from??a,s=e.through??m(o,180);if(!p(o)||!p(s)||o>s)return{ok:!1,error:`INVALID_DATE_RANGE`};if((Date.parse(`${s}T00:00:00Z`)-Date.parse(`${o}T00:00:00Z`))/864e5+1>366)return{ok:!1,error:`DATE_RANGE_TOO_LARGE`,maxDays:366};let c,l;try{if(l=await Mt(t,s),c=Ft(l.events,e.locale,[!0,`true`].includes(e.strict)),r){let e=r.split(`#`)[0];c=c.filter(t=>t.id===e)}}catch(e){if(e instanceof ft)return{ok:!1,error:`EVENT_LIMIT_EXCEEDED`,maxEvents:e.limit};throw e}let u=M(c,o,s),d=e.category?x(e.category):``,f=d?u.filter(e=>e.categories.some(e=>x(e)===d)):u;if(r&&r.includes(`#`)&&(f=f.filter(e=>e.id===r)),f.length>1e4)return{ok:!1,error:`OCCURRENCE_LIMIT_EXCEEDED`};if(l.native){let[n,r]=await Promise.all([Nt(t,f,l.schema),It(t,f,[void 0,!0,`true`].includes(e.publicUrls))]);return{ok:!0,from:o,through:s,cache:Vt(l.schema,i,e.from===void 0),events:r.map(e=>Ue(e,n,t.site.url,t.plugin.id))}}let[h,g]=await Promise.all([Ot(t,f.flatMap(e=>e.venueId?[e.venueId]:[])),jt(t,f.flatMap(e=>e.organizerId?[e.organizerId]:[]))]);return{ok:!0,from:o,through:s,events:f.map(e=>Be(e,e.venueId?h.get(e.venueId):void 0,t.plugin.id,e.organizerId?g.get(e.organizerId):void 0))}}async function Gt(e,t,n){let r=e,a=await B(t);if(!a)return{blocks:[{type:`context`,text:`Choose an event collection in Event settings.`}]};let o=(e,n)=>({type:`link`,label:n,target:{kind:`external`,url:new URL(e,t.site.url).href}}),s=`/_emdash/admin/content/`+encodeURIComponent(a.slug);if(r.page===`widget:upcoming-events`)return{blocks:[{type:`header`,text:`Upcoming events`},...((await Ut({},t)).events??[]).slice(0,5).map(e=>({type:`section`,block_id:`eventual-verbatim`,text:e.title+` · `+e.start}))]};let c=[{type:`header`,text:`Events`},{type:`context`,text:`Create and edit announcements in EmDash. Save first, then open the Dates, venue & repeat panel.`}];if(r.action_id===`duplicate-event`){(!n||typeof r.value!=`string`)&&i(`Sign in before creating a copy.`);let e=await t.content.get(a.slug,r.value);e||i(`This event no longer exists.`);let l=Bt((e.draftRevisionId?await t.content.getRevision?.(a.slug,e.id,e.draftRevisionId):void 0)?.data??e.data),u=new Set(a.fields.filter(e=>!e.validation?.relation).map(e=>e.slug)),d=await t.content.create(a.slug,Object.fromEntries(Object.entries({...l,title:String(l.title??`Event`)+` (copy)`}).filter(([e])=>u.has(e))),{locale:e.locale??void 0});c.push({type:`context`,text:`Draft copy created.`},{type:`actions`,elements:[o(s+`/`+encodeURIComponent(d.id),`Edit the copy`)]})}else r.action_id&&!String(r.action_id).startsWith(`page-native-events`)&&i(`Reload the workspace before trying this action.`);let l=await F(t);c.push({type:`actions`,elements:[o(s+`/new`,`Create event`),o(s,`All events`),...[`venue`,`organizer_ref`].flatMap(e=>{let t=I(a,e);return l.some(e=>e.slug===t)?[o(`/_emdash/admin/content/`+encodeURIComponent(t),e===`venue`?`Manage venues`:`Manage organizers`)]:[]})]});let u=String(r.action_id).startsWith(`page-native-events`)?String(r.value||``):void 0,d=await t.content.list(a.slug,{limit:20,cursor:u});c.push({type:`table`,page_action_id:`page-native-events`,columns:[{key:`title`,label:`Event`},{key:`locale`,label:`Language`},{key:`status`,label:`Publication`,format:`badge`},{key:`edit`,label:`Edit`,format:`element`},...n?[{key:`copy`,label:`Copy`,format:`element`}]:[]],rows:d.items.map(e=>({title:String(e.data.title||e.slug),locale:e.locale??``,status:e.status,edit:o(s+`/`+encodeURIComponent(e.id),`Edit`),...n?{copy:{type:`button`,action_id:`duplicate-event`,label:`Duplicate`,value:e.id}}:{}})),empty_text:`No events yet.`}),d.hasMore&&(!d.cursor||d.cursor===u)&&i(`Incomplete event page. Reload the workspace.`);let f=[...u?[{type:`button`,action_id:`page-native-events-first`,label:`First page`,value:``}]:[],...d.hasMore?[{type:`button`,action_id:`page-native-events-next`,label:`Next events`,value:d.cursor}]:[]];return f.length&&c.push({type:`actions`,elements:f}),c.push({type:`header`,text:`Subscribe`},{type:`actions`,elements:[o(`/_emdash/api/plugins/eventual/calendar`,`Calendar subscription (.ics)`),o(`/_emdash/api/plugins/eventual/publicEvents`,`Published events (JSON)`)]}),{blocks:c}}const Kt=e=>({type:`context`,text:e}),qt=()=>({type:`actions`,elements:[[`/events`,`Events`],[`/venues`,`Venues`],[`/organizers`,`Organizers`],[`/settings`,`Settings`]].map(([e,t])=>({type:`button`,action_id:`open-page:`+e,label:t,value:e}))}),Jt=(e,t,n)=>({type:`actions`,elements:[{type:`link`,label:n,target:{kind:`external`,url:new URL(`/_emdash/admin/content/`+encodeURIComponent(t),e.site.url).href}}]});async function Yt(e,t){let n=await Ze(e),r=await Qe(e),i=await F(e),a=i.find(e=>e.slug===`events`),o=(e,t)=>String(a?.fields.find(t=>t.slug===e)?.options?.collection??t),s=(e,t)=>({type:`select`,action_id:e,label:t,options:[{value:``,label:e===`events`?`Choose a collection`:`No collection`},...i.map(e=>({value:e.slug,label:(e.label||e.slug)+` (`+e.slug+`)`}))],initial_value:n?.[e]??(e===`events`?a?.slug??``:i.some(t=>t.slug===o(e===`venues`?`venue`:`organizer_ref`,e))?o(e===`venues`?`venue`:`organizer_ref`,e):``)});return{blocks:[qt(),{type:`header`,text:`Settings`},Kt(`Choose content types.`),...t?[{type:`banner`,title:`Settings not saved`,description:t,variant:`error`}]:[],{type:`form`,block_id:`collection-settings:`+Object.values(n??{}).join(`:`),fields:[s(`events`,`Event collection`),s(`venues`,`Venue collection`),s(`organizers`,`Organizer collection`)],submit:{action_id:`save-settings`,label:`Save settings`}},{type:`form`,block_id:`legacy-reads:`+r,fields:[{type:`toggle`,action_id:`legacyReads`,label:`Show old events saved inside the plugin`,description:`Enable to serve old plugin events.`,initial_value:r}],submit:{action_id:`save-legacy-reads`,label:`Save switch`}},{type:`actions`,elements:[{type:`link`,label:`Setup guide`,target:{kind:`external`,url:`https://github.com/Vermeulen-Solutions/eventual-emdash-sandbox`}}]}]}}async function Xt(e,t,n){t=R(t);let r=e&&typeof e==`object`&&!Array.isArray(e)?{...e}:{};if(r.type===`form_submit`&&(!r.values||typeof r.values!=`object`||Array.isArray(r.values)))return{blocks:[{type:`banner`,title:`Invalid admin request`,variant:`error`}]};String(r.action_id??``).startsWith(`open-page:`)&&(r.type=`page_load`,r.page=r.value,delete r.action_id);let a=r.page;if(a===`/settings`||r.action_id===`save-settings`||r.action_id===`save-legacy-reads`){if(!n||n.role<50)return{blocks:[qt(),Kt(`Only an administrator can change these settings.`)]};if(r.action_id===`save-legacy-reads`)try{let e=r.values?.legacyReads;e===!0||e===!1||e===`true`||e===`false`||i(`The legacy read setting must be on or off.`),await $e(t,e===!0||e===`true`)}catch(e){return Yt(t,e instanceof Error?e.message:`Check the legacy read setting.`)}if(r.action_id===`save-settings`)try{let e=r.values;(!e||e.defaultTimezone!==void 0&&!h(String(e.defaultTimezone)))&&i(`Choose a valid IANA time zone.`),await nt(t,{events:String(e.events??``),venues:String(e.venues??``),organizers:String(e.organizers??``)}),e.defaultTimezone!==void 0&&await t.settings.set(`defaultTimezone`,String(e.defaultTimezone))}catch(e){return Yt(t,e instanceof Error?e.message:`Check the collection settings.`)}return Yt(t)}try{let e=await et(t);if(!e.schema){let e=await Qe(t);return{blocks:[qt(),{type:`header`,text:`Connect events to a content type`},Kt(`Choose an event content type.`),Kt(e?`Public calendars show old plugin events.`:`Turn on "Show old events saved inside the plugin" in settings if needed.`),Kt(`You can copy the old events into a content type. See the setup guide.`)]}}if(a===`/venues`||a===`/organizers`){let n=a===`/venues`?e.venues:e.organizers;return{blocks:[qt(),Kt(`Create and edit these entries in the EmDash content editor.`),...n?[Jt(t,n,a===`/venues`?`Manage venues`:`Manage organizers`)]:[Kt(`No collection selected. Ask an administrator to configure it in Event settings.`)]]}}return{blocks:[qt(),...(await Gt(r,t,n)).blocks]}}catch(e){return{blocks:[qt(),{type:`banner`,title:`Review collection settings`,description:e instanceof Error?e.message:`Collections could not be loaded.`,variant:`error`}]}}}const Zt=new Set([`label`,`text`,`title`,`description`,`placeholder`,`empty_text`,`confirm`,`deny`,`message`]),Qt=new Set([`venueId`,`organizerId`,`venue`,`organizer_ref`,`imageMediaId`,`timezone`,`eventIds`,`events`,`venues`,`organizers`]);function $t(e,t){let n=e=>{if(Array.isArray(e))return e.map(n);if(!e||typeof e!=`object`)return e;let r=e;return String(r.block_id).startsWith(`eventual-verbatim`)?r:Object.fromEntries(Object.entries(r).map(([e,i])=>[`value`,`initial_value`,`target`,`condition`,`patch`].includes(e)?[e,i]:e===`options`&&Qt.has(String(r.action_id))?[e,i.map(e=>e.value===``?{...e,label:t(e.label)}:e)]:e===`rows`?[e,i.map(e=>Object.fromEntries(Object.entries(e).map(([e,i])=>{if(typeof i!=`string`)return[e,n(i)];let a=i[0]?.toUpperCase()+i.slice(1),o=r.columns.some(t=>t.key==e&&t.format==`badge`)?t(a):e==`effective`?t(i):i;return[e,o==a?i:o]})))]:e===`label`&&r.action_id===`edit-organizer`?[e,i]:[e,Zt.has(e)&&typeof i==`string`?t(i):n(i)]))};return n(e)}const en=new Map;function tn(e){let t=0,n=(n,r)=>{let a=[],o=``,s=()=>{o&&a.push(o),o=``};for(;t<e.length;){let c=e[t];if(c===`{`)s(),t++,a.push(i(n));else if(c===`}`&&r)break;else c===`#`&&n?(s(),a.push(0),t++):(o+=c,t++)}return s(),a},r=()=>{for(;e[t]===` `;)t++;let n=t;for(;t<e.length&&!/[\s,{}]/.test(e[t]);)t++;let r=e.slice(n,t);for(;e[t]===` `||e[t]===`
11
+ `),a=e.location||``;e.locationType===`virtual`?a=r||a:e.locationType===`hybrid`&&r&&a&&(a=`${a} · ${r}`);let o,s,c,l=``;if(e.allDay){let t=e.start.slice(0,10).replace(/-/g,``),n=new Date(e.end.slice(0,10)+`T00:00:00Z`);n.setUTCDate(n.getUTCDate()+1),o=`${t}/${n.toISOString().slice(0,10).replace(/-/g,``)}`,s=e.start.slice(0,10),c=n.toISOString().slice(0,10),l=`&allday=true`}else{let t=new Date(e.start).toISOString(),n=new Date(e.end).toISOString();o=`${t.replace(/[-:]/g,``).replace(/\.\d{3}/,``)}/${n.replace(/[-:]/g,``).replace(/\.\d{3}/,``)}`,s=t,c=n}let u=encodeURIComponent,d=`https://calendar.google.com/calendar/render?action=TEMPLATE&text=${u(n)}&dates=${o}&details=${u(i)}&location=${u(a)}`,f=`path=/calendar/action/compose&rru=addevent&subject=${u(n)}&body=${u(i)}&location=${u(a)}&startdt=${u(s)}&enddt=${u(c)}${l}`,p=`https://outlook.live.com/calendar/0/deeplink/compose?${f}`,m=`https://outlook.office.com/calendar/0/deeplink/compose?${f}`,h=e.id.split(`#`)[0],g=`/_emdash/api/plugins/eventual/calendar?eventId=${u(h)}`;return{google:d,outlook:p,office365:m,ics:t?new URL(g,t).href:g}}function ke(e,t){if(typeof e!=`string`||!e.trim())return``;try{let n=t?new URL(e,t):new URL(e);return n.protocol===`http:`||n.protocol===`https:`?n.href:``}catch{return``}}function Ae(e){let t=ke(e.virtualUrl??``);return e.locationType===`virtual`?t||e.location:e.locationType===`hybrid`?[e.location,t].filter(Boolean).join(` · `):e.location}function je(e){return ke(e.externalUrl)||(e.locationType===`virtual`||e.locationType===`hybrid`?ke(e.virtualUrl??``):``)}function Me(e){return e.status===`cancelled`?`CANCELLED`:e.status===`postponed`?`TENTATIVE`:`CONFIRMED`}function Ne(e){if(typeof e!=`string`||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,3})?)?(?:Z|[+-]\d{2}:\d{2})$/.test(e))return!1;let t=e.slice(11,19).split(`:`);return p(e.slice(0,10))&&Number.isFinite(Date.parse(e))&&Number(t[0])<=23&&Number(t[1])<=59&&(!t[2]||Number(t[2])<=59)}function P(e){if(typeof e!=`string`)return e??void 0;if(e.trim())try{return JSON.parse(e)}catch{i(`Invalid JSON.`)}}const Pe=[`start`,`end`,`start_date`,`end_date`,`all_day`,`timezone`,`recurrence`,`exceptions`,`occurrence_content`,`venue`,`venue_id`,`organizer_ref`,`organizer_id`,`location_type`,`event_status`,`calendar_uid`,`legacy_id`,`categories`,`virtual_url`,`external_url`,`image_url`,`organizer_details`,`previous_start_date`,`schedule_history`];function Fe(e,t={}){let n={...e},r=e.all_day??e.allDay??!1,a=r===0?!1:r===1?!0:r;typeof a!=`boolean`&&i(`all_day must be a boolean.`);let o=e.timezone??`Europe/Zurich`;(typeof o!=`string`||!h(o))&&i(`Invalid IANA timezone.`);let s=a?e.start_date??e.start:e.start,c=a?e.end_date??e.end:e.end;(typeof s!=`string`||typeof c!=`string`||!s||!c)&&i(`Start and end are required.`);let l=s,u=c;if(a)(e.start_date!=null&&!p(l)||e.end_date!=null&&!p(u))&&i(`All-day date fields must use YYYY-MM-DD.`),[l,u].some(e=>!p(e)&&!Ne(e))&&i(`Invalid all-day date representation.`),l=l.slice(0,10),u=u.slice(0,10),(!p(l)||!p(u)||u<l)&&i(`Invalid inclusive all-day dates.`),n.start_date=l,n.end_date=u,delete n.start,delete n.end;else{let e=e=>{if(Ne(e))return new Date(e).toISOString()},t=e(l),r=e(u);if(t&&r)l=t,u=r;else{let e=y({start:l,end:u,allDay:!1,timezone:o});e.dates||i(`Invalid local datetime or timezone.`),{start:l,end:u}=e.dates}Date.parse(u)<Date.parse(l)&&i(`End must be at or after start.`),n.start=l,n.end=u,delete n.start_date,delete n.end_date}let d=P(e.recurrence);if(d!=null&&!O(d)&&i(`Invalid recurrence rule.`),d&&O(d)){let e=a?l:_(l,o)?.slice(0,10);(!e||d.until<e)&&i(`Recurrence until precedes start.`),!a&&(new Date(l).getUTCSeconds()||new Date(l).getUTCMilliseconds())&&i(`Recurring starts require minute precision.`)}let f=P(e.exceptions)??[];(!Array.isArray(f)||f.length>500)&&i(`Exceptions must be an array of at most 500 items.`);let m=new Set([`start`,`end`,`allDay`,`timezone`,`locationType`,`virtualUrl`,`status`,`externalUrl`,`imageUrl`,`imageMediaId`,`categories`]),g={id:`validation`,start:l,end:u,allDay:a,timezone:o,recurrence:d,exceptions:f,published:!0};for(let e of f)if((!e||typeof e!=`object`||typeof e.recurrenceId!=`string`||![`cancelled`,`modified`].includes(e.status))&&i(`Invalid exception.`),e.status===`modified`){(!e.overrides||typeof e.overrides!=`object`||Array.isArray(e.overrides)||!Object.keys(e.overrides).length)&&i(`Modified exceptions require overrides.`),Object.keys(e.overrides).some(e=>!m.has(e))&&i(`Editorial exception overrides belong in occurrence_content.`);let t=j(g,e.recurrenceId);t||i(`Exception is not a scheduled occurrence.`);let n={...t,...e.overrides};(typeof n.allDay!=`boolean`||!h(n.timezone))&&i(`Invalid exception timezone or allDay.`),(n.allDay?!p(n.start)||!p(n.end)||n.end<n.start:!Number.isFinite(Date.parse(n.start))||!Number.isFinite(Date.parse(n.end))||Date.parse(n.end)<Date.parse(n.start))&&i(`Invalid exception schedule.`),!n.allDay&&[n.start,n.end].some(e=>!Ne(e))&&i(`Timed exceptions require ISO instants.`);for(let t of[`locationType`,`virtualUrl`,`status`,`externalUrl`,`imageUrl`,`imageMediaId`])t in e.overrides&&typeof e.overrides[t]!=`string`&&i(`Exception field must be text: `+t);e.overrides.locationType!==void 0&&![`physical`,`virtual`,`hybrid`].includes(e.overrides.locationType)&&i(`Invalid exception location type.`),e.overrides.status!==void 0&&![`published`,`cancelled`,`postponed`,`rescheduled`].includes(e.overrides.status)&&i(`Invalid exception status.`);for(let t of[`virtualUrl`,`externalUrl`,`imageUrl`])e.overrides[t]&&!ke(e.overrides[t])&&i(`Exception URLs must use HTTP(S).`);e.overrides.categories!==void 0&&(!Array.isArray(e.overrides.categories)||e.overrides.categories.some(e=>typeof e!=`string`))&&i(`Exception categories must be an array of strings.`)}f.length&&(!d||!Ce(g))&&i(`Duplicate or invalid exception recurrence IDs.`);let v=P(e.occurrence_content)??[];(!Array.isArray(v)||v.length>500||v.some(e=>!e||typeof e.recurrenceId!=`string`||!e.overrides||Object.keys(e.overrides).some(e=>![`title`,`description`,`location`,`organizer`].includes(e))))&&i(`Invalid occurrence_content.`),(new Set(v.map(e=>e.recurrenceId)).size!==v.length||!t.allowStaleOccurrenceCopy&&v.some(e=>!d||!j(g,e.recurrenceId)))&&i(`Invalid editorial recurrence IDs.`);for(let e of v)for(let[t,n]of Object.entries(e.overrides))(t===`description`?typeof n!=`string`&&!Array.isArray(n):typeof n!=`string`)&&i(`Invalid occurrence copy field: `+t);e.location_type!=null&&![`physical`,`virtual`,`hybrid`].includes(String(e.location_type))&&i(`Invalid location type.`),e.event_status!=null&&![`published`,`cancelled`,`postponed`,`rescheduled`].includes(String(e.event_status))&&i(`Invalid event status.`);for(let t of[`virtual_url`,`external_url`,`image_url`])e[t]&&(typeof e[t]!=`string`||!ke(e[t]))&&i(`Public URLs must use HTTP(S): `+t);let b=P(e.organizer_details);b!=null&&(typeof b!=`object`||Array.isArray(b)||[`id`,`name`,`website`,`contactUrl`].some(e=>typeof b[e]!=`string`)||[`website`,`contactUrl`].some(e=>{let t=b[e];return t&&!ke(t)}))&&i(`Invalid organizer details.`),e.previous_start_date&&!p(e.previous_start_date)&&!Ne(e.previous_start_date)&&i(`Invalid previous start date.`);let x=P(e.schedule_history);return x!=null&&(!Array.isArray(x)||x.length>10||x.some(e=>!e||!Ne(e.changedAt)||!h(e.timezone)||typeof e.allDay!=`boolean`||(e.allDay?!p(e.start)||!p(e.end)||e.end<e.start:!Ne(e.start)||!Ne(e.end)||Date.parse(e.end)<Date.parse(e.start))))&&i(`Invalid schedule history.`),n.all_day=a,n.timezone=o,S(e.categories),e.calendar_uid!=null&&(typeof e.calendar_uid!=`string`||!/^[A-Za-z0-9.!~*'()%_-]+@[A-Za-z0-9.-]+$/.test(e.calendar_uid))&&i(`Invalid calendar UID.`),n}const Ie=new Set([`image/avif`,`image/gif`,`image/jpeg`,`image/png`,`image/webp`]),Le=8*1024*1024;function Re(e){return Ie.has(e.toLowerCase())}function ze(e,t){let n=new URLSearchParams({eventId:t});return`/_emdash/api/plugins/${encodeURIComponent(e)}/publicEventImage?${n}`}function Be(e,t,n=`eventual`,r){let i=w(t,e.location);return{...e.locale?{locale:e.locale}:{},...e.translationGroup?{translationGroup:e.translationGroup}:{},id:e.id,updatedAt:e.updatedAt,title:e.title,description:e.description,...e.descriptionBlocks?{descriptionBlocks:e.descriptionBlocks}:{},start:e.start,end:e.end,allDay:e.allDay,timezone:e.timezone,location:i,locationType:e.locationType??`physical`,...E(e.virtualUrl??``)?{virtualUrl:E(e.virtualUrl??``)}:{},status:ce(e.published,e.status),organizer:r?.name??(e.organizer||e.organizerDetails?.name||``),...r?{organizerDetails:{id:r.id,name:r.name,website:E(r.website),contactUrl:E(r.contactUrl)}}:e.organizerDetails?{organizerDetails:e.organizerDetails}:{},...e.status===`rescheduled`&&e.previousStartDate?{previousStartDate:e.previousStartDate}:{},externalUrl:e.externalUrl,imageUrl:e.featuredMediaId||e.imageMediaId?e.imageUrl?.includes(`publicEventImage`)?e.imageUrl:ze(n,e.id):e.imageUrl||``,...e.imageMedia?{imageMedia:e.imageMedia}:{},categories:b(e.categories),venue:t?{id:t.id,name:t.name,address:C(t),addressParts:{street:t.street,street2:t.street2,locality:t.locality,region:t.region,postalCode:t.postalCode,country:t.country}}:null,directionsUrl:T(i),calendarLinks:Oe({id:e.id,title:e.title,description:e.description,start:e.start,end:e.end,allDay:e.allDay,timezone:e.timezone,location:i,locationType:e.locationType,virtualUrl:e.virtualUrl})}}const Ve=e=>e instanceof Date?e.toISOString():a(e);function He(e){if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=e,n=!!t.data&&typeof t.data==`object`&&!Array.isArray(t.data),r=n?t.data:t,i=a(n&&t.type?t.id:r.id??t.id);if(!i)return null;try{let e=P(r.exceptions)??[];if(!Array.isArray(e))return null;let o=Object.hasOwn(r,`all_day`)||n&&(typeof t.type==`string`||!Object.hasOwn(r,`published`)),s=o?e:e.map(e=>({...e,overrides:e.overrides?Object.fromEntries(Object.entries(e.overrides).filter(([e])=>![`title`,`description`,`location`,`organizer`,`locale`].includes(e))):void 0})).filter(e=>e.status===`cancelled`||Object.keys(e.overrides??{}).length),c=Fe({...r,all_day:r.all_day??r.allDay,exceptions:s},{allowStaleOccurrenceCopy:!0}),l=c.all_day,u=a(l?c.start_date:c.start),d=a(l?c.end_date:c.end),f=P(r.recurrence),p=e.map(e=>({...e,overrides:e.overrides?{...e.overrides}:void 0})),m=P(r.occurrence_content)??[];for(let e of m){if(!f||!j({id:i,start:u,end:d,allDay:l,timezone:a(c.timezone),recurrence:f},e.recurrenceId))continue;let t=p.find(t=>t.recurrenceId===e.recurrenceId);t?.status!==`cancelled`&&(t?t.overrides={...t.overrides,...e.overrides}:p.push({recurrenceId:e.recurrenceId,status:`modified`,overrides:e.overrides}))}let h=o?n&&typeof t.status==`string`?t.status:r.status:void 0,g=h?h===`published`:r.published===!0,_=r.event_status??([`cancelled`,`postponed`,`rescheduled`].includes(a(r.status))?r.status:g?`published`:`draft`),v=typeof r.featured_image==`string`?P(r.featured_image):r.featured_image,y=Object.hasOwn(r,`venue_id`)?r.venue_id:r.venue??r.venueId,b=typeof y==`string`?y:y&&typeof y==`object`?a(y.id):``,x=S(r.categories),C=a(v?.id??r.featuredMediaId??r.featured_media_id??r.imageMediaId),w=v?.meta?.storageKey,T=a(v?.src||v?.url)||(w?`/_emdash/api/media/file/`+encodeURIComponent(String(w)):``),E=e=>typeof e==`number`&&e>0?e:void 0,D=T?{src:T,width:E(v?.width),height:E(v?.height),alt:a(v?.alt)||void 0}:void 0;return{id:i,title:a(r.title).trim(),description:typeof r.description==`string`?r.description:JSON.stringify(r.description??[]),descriptionBlocks:Array.isArray(r.description)?r.description:void 0,start:u,end:d,allDay:l,timezone:a(c.timezone),published:g,status:_,recurrence:f,exceptions:p,location:a(r.location),locationType:r.location_type??r.locationType??`physical`,virtualUrl:a(r.virtual_url??r.virtualUrl),externalUrl:a(r.external_url??r.externalUrl),organizer:a(r.organizer),organizerId:a(Object.hasOwn(r,`organizer_id`)?r.organizer_id:typeof r.organizer_ref==`object`?r.organizer_ref?.id:r.organizer_ref??r.organizerId),organizerDetails:P(r.organizer_details),venueId:b,imageUrl:C?``:a(r.image_url??r.imageUrl??v?.src??v?.url),imageMediaId:C,featuredMediaId:C||void 0,imageMedia:D,categories:x,createdAt:Ve(t.createdAt??r.created_at??r.createdAt)||`1970-01-01T00:00:00.000Z`,updatedAt:Ve(t.updatedAt??r.updated_at??r.updatedAt)||`1970-01-01T00:00:00.000Z`,locale:a(t.locale??r.locale)||void 0,translationGroup:a(t.translationGroup??r.translation_group??r.translationGroup??t.translation_group)||void 0,calendarUid:a(r.calendar_uid??r.calendarUid)||void 0,calendarSequence:typeof r.calendarSequence==`number`?r.calendarSequence:void 0,previousStartDate:a(r.previous_start_date??r.previousStartDate)||void 0,scheduleHistory:P(r.schedule_history??r.scheduleHistory),slug:a(t.slug??r.slug)||void 0,publicUrl:a(t.publicUrl??t.url??r.publicUrl??r.url)||void 0}}catch{return null}}function Ue(e,t,n,r=`eventual`){let i=Ee(t,e),a=Be(e,i?{...i,street:i.street??``,street2:i.street2??``,locality:i.locality??``,region:i.region??``,postalCode:i.postalCode??``,country:i.country??``,createdAt:``,updatedAt:``}:void 0,r),o=a.imageUrl||e.imageUrl;if(n&&o)try{o=new URL(o,n).href}catch{o=``}let s=e.imageMedia,c=s?{...s,src:n&&s.src.startsWith(`/`)?new URL(s.src,n).href:s.src}:void 0;return{...a,description:N(e.description),...e.descriptionBlocks?{descriptionBlocks:e.descriptionBlocks}:{},imageUrl:o,...c?{imageMedia:c}:{},organizerDetails:e.organizerDetails,previousStartDate:e.previousStartDate,locale:e.locale,translationGroup:e.translationGroup,slug:e.slug,publicUrl:e.publicUrl}}const We=new WeakMap;function Ge(e,t,n){let r=We.get(e);return r||We.set(e,r=Object.create(null)),r[t]??=Promise.resolve().then(n)}function Ke(e,t){let n=We.get(e);n&&delete n[t]}const qe=`collections`,Je=`legacyReads`,Ye=/^[a-z][a-z0-9_]{0,62}$/;async function Xe(e){return(await Ze(e))?.events??`events`}function Ze(e){return Ge(e,`collection-settings`,async()=>await e.settings?.get(qe)??void 0)}function Qe(e){return Ge(e,`legacy-reads`,async()=>await e.settings?.get(Je)===!0)}async function $e(e,t){await e.settings.set(Je,t),Ke(e,`legacy-reads`)}function F(e){return Ge(e,`schemas`,async()=>await e.schema?.listCollections()??[])}function et(e){return Ge(e,`bindings`,()=>tt(e))}async function tt(e){let[t,n]=await Promise.all([Ze(e),F(e)]);t&&(!t.events||Object.values(t).some(e=>typeof e!=`string`||e!==``&&!Ye.test(e)))&&i(`Invalid collections. Choose them again in Event settings.`);let r=t?.events??`events`,a=n.find(e=>e.slug===r);t&&!a&&i(`The selected event collection is missing.`);let o=(e,t)=>{let n=a?.fields?.find(t=>t.slug===e);return String(n?.validation?.targetCollection??n?.options?.collection??t)},s={events:r,venues:t?.venues??o(`venue`,`venues`),organizers:t?.organizers??o(`organizer_ref`,`organizers`)};if(t)for(let e of[s.venues,s.organizers])e&&!n.some(t=>t.slug===e)&&i(`Selected directory missing. Review Event settings.`);return{...s,schema:a,schemas:n,configured:!!t}}async function nt(e,t){(!t.events||Object.values(t).some(e=>typeof e!=`string`||e!==``&&!Ye.test(e)))&&i(`Choose valid collection names.`);let n=await F(e),r=n.find(e=>e.slug===t.events);r||i(`Choose an existing event collection.`);for(let[e,t]of Object.entries({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`})){let n=r.fields.find(t=>t.slug===e);(!n||n.type!==t)&&i(`Event collection needs `+e+` (`+t+`). Apply the event blueprint first.`);let a=[`title`,`description`,`occurrence_content`].includes(e);n.translatable!==a&&i(`Set `+e+` translatable to `+a+` before selecting this collection.`)}for(let[e,a]of[[`venues`,`venue`],[`organizers`,`organizer_ref`]]){let o=t[e],s=n.find(e=>e.slug===o);o&&(!s||!s.fields.some(e=>[`name`,`title`].includes(e.slug)&&e.type===`string`))&&i(`Choose a `+e+` collection with a name or title field.`);let c=r.fields.find(e=>e.slug===a),l=r.fields.find(t=>t.slug===(c?.validation?.relation?e===`venues`?`venue_id`:`organizer_id`:a)),u=l?.validation?.targetCollection??l?.options?.collection;o&&(l?.type!==`reference`||u!==o)&&i(`Set the event `+a+` reference target to `+o+` first.`),!o&&l&&i(`This event schema has a `+a+` reference. Select its target collection.`),l?.translatable!==void 0&&l.translatable!==!1&&i(`Event references must be shared across languages.`)}await e.settings.set(qe,t),Ke(e,`collection-settings`),Ke(e,`bindings`)}function rt(e){if(typeof e==`string`)return e.trim()||void 0;if(e&&typeof e==`object`&&!Array.isArray(e))return rt(e.id)}function I(e,t){let n=e?.fields.find(e=>e.slug===t),r=n?.validation?.targetCollection??n?.options?.collection;return typeof r==`string`&&r?r:t===`venue`?`venues`:`organizers`}function it(e,t){return(e?.fields.find(e=>e.slug===t))?.validation?.relation?t===`venue`?`venue_id`:`organizer_id`:t}async function L(e){return(await et(e)).schema}var at=class extends Error{constructor(){super(`The sandbox RPC budget is exceeded.`),this.name=`SandboxBudgetError`}};const ot=Symbol(`eventual invocation budget`),st=new WeakMap;function R(e){if(e[ot])return e;let t=st.get(e);if(t)return t;let n={used:0,reserved:0},r={...e,[ot]:n},i=e=>new Proxy(e,{get(e,t){let r=Reflect.get(e,t,e);return typeof r==`function`?(...t)=>{if(n.used+n.reserved>=10)throw new at;return n.used++,Reflect.apply(r,e,t)}:r}});for(let[t,n]of Object.entries(e))![`site`,`plugin`,`storage`].includes(t)&&n&&typeof n==`object`&&(r[t]=i(n));return e.storage&&(r.storage=new Proxy(e.storage,{get(e,t){let n=Reflect.get(e,t,e);return n&&typeof n==`object`?i(n):n}})),st.set(e,r),r}function ct(e,t){let n=e[ot];if(!n)return()=>{};if(n.used+n.reserved+t>10)throw new at;n.reserved+=t;let r=!1;return()=>{r||=(n.reserved-=t,!0)}}function lt(e){let t=e[ot];return t?10-t.used-t.reserved:10}function ut(e,t){if(!e)return{...t,calendarSequence:t.calendarSequence??Math.floor(Date.now()/1e3)};let n=Math.max(e.calendarSequence??(Math.floor(Date.parse(e.updatedAt)/1e3)||0),t.calendarSequence??0)+1;n>2147483647&&i(`Calendar sequence exhausted.`);let r=e.start!==t.start||e.end!==t.end||e.allDay!==t.allDay||e.timezone!==t.timezone,a=r?[{start:e.start,end:e.end,allDay:e.allDay,timezone:e.timezone,changedAt:t.updatedAt},...e.scheduleHistory??[]].slice(0,10):e.scheduleHistory;return{...t,calendarSequence:n,...a?{scheduleHistory:a}:{},...r?{previousStartDate:e.start}:e.previousStartDate?{previousStartDate:e.previousStartDate}:{}}}const dt=1e4;var ft=class extends Error{constructor(e){super(`More than ${e} events matched the request. Narrow the query or contact the site administrator.`),this.limit=e,this.name=`EventScanLimitError`}};function pt(e){return e.storage.events}function mt(e){return e.storage.venues}function ht(e){return e.storage.calendar_cancellations}function z(e,t){return pt(e).get(t)}function gt(e,t){return vt(e,t)}function _t(e){return new Date(Math.max(Date.now(),Date.parse(e??``)+1||0)).toISOString()}async function vt(e,t){let n=await pt(e).get(t.id);t=ut(n,t);let r=await bt(e,n,t);await pt(e).put(t.id,t);for(let t=0;t<r.length;t+=100)await ht(e).deleteMany(r.slice(t,t+100));return t}async function yt(e,t){return await bt(e,await pt(e).get(t),null),pt(e).delete(t)}async function bt(e,t,n){let r=new Date().toISOString().slice(0,10),i=new Date(`${r}T00:00:00Z`);i.setUTCDate(i.getUTCDate()+365);let a=i.toISOString().slice(0,10),o=t?.published?M([t],r,a):[],s=n?.published?M([n],r,a):[],c=new Set(s.map(e=>e.id)),l=(e,t)=>`locale:`+e.toLowerCase()+`:`+t,u=[...c,...s.flatMap(e=>Object.keys(n?.translations??{}).map(t=>l(t,e.id)))],d=o.filter(e=>!c.has(e.id)),f=Object.keys(t?.translations??{}).filter(e=>!Object.hasOwn(n?.translations??{},e)),p=n?o.flatMap(e=>f.map(t=>({item:e,locale:t}))):[],m=new Date().toISOString(),h=p.map(({item:e,locale:r})=>({id:l(r,e.id),data:{id:e.id,eventId:t.id,start:e.start,end:e.end,allDay:e.allDay,timezone:e.timezone,cancelledAt:m,locale:r.toLowerCase(),categories:e.categories,calendarUid:t.calendarUid,translationGroup:t.translationGroup,calendarSequence:n?.calendarSequence}}));return d.length&&h.push(...d.map(e=>({id:e.id,data:{id:e.id,eventId:t.id,start:e.start,end:e.end,allDay:e.allDay,timezone:e.timezone,cancelledAt:m,translationGroup:e.translationGroup??t.translationGroup,calendarUid:t.calendarUid,calendarSequence:n?.calendarSequence??(t.calendarSequence??Math.floor(Date.parse(t.updatedAt)/1e3))+1,categories:e.categories,locales:e.locale?[e.locale.toLowerCase(),...Object.keys(t.translations??{}).map(e=>e.toLowerCase())]:void 0}}))),h.length&&await ht(e).putMany(h),u}async function xt(e){let t=[],n;do{let r=await ht(e).query({limit:100,cursor:n});if(t.push(...r.items.map(e=>e.data)),r.hasMore&&(!r.cursor||r.cursor===n)&&i(`Incomplete cancellation cursor.`),t.length>dt)throw new ft(dt);n=r.hasMore?r.cursor:void 0}while(n);return t}function St(e,t){return mt(e).get(t)}function Ct(e,t){return mt(e).put(t.id,t)}function wt(e,t){return mt(e).delete(t)}async function Tt(e,t){return await pt(e).count({venueId:t})>0}async function Et(e,t={}){let n=[],r=t.maxItems??dt;if(!Number.isInteger(r)||r<1||r>dt)throw RangeError(`maxItems must be between 1 and ${dt}`);let a,o=t.through?new Date(Date.parse(`${t.through}T00:00:00Z`)+2*864e5).toISOString().slice(0,10):void 0,s=new Set;do{let c=await pt(e).query({where:{...t.published===void 0?{}:{published:t.published},...o?{start:{lt:o}}:{}},orderBy:{start:t.order??`asc`},limit:Math.min(100,r-n.length),cursor:a});if(n.push(...c.items.map(e=>e.data)),c.hasMore&&!c.cursor&&i(`Event storage returned an incomplete page without a cursor.`),c.hasMore&&s.has(c.cursor)&&i(`Event storage returned a repeated cursor.`),c.cursor&&s.add(c.cursor),a=c.hasMore?c.cursor:void 0,a&&n.length>=r)throw new ft(r)}while(a);return n}async function Dt(e){let t=[],n;do{let r=await mt(e).query({orderBy:{name:`asc`},limit:100,cursor:n});if(t.push(...r.items.map(e=>e.data)),r.hasMore&&(!r.cursor||r.cursor===n)&&i(`Incomplete venue cursor.`),t.length>5e3)throw new ft(5e3);n=r.hasMore?r.cursor:void 0}while(n);return t}async function Ot(e,t){return t.length?mt(e).getMany([...new Set(t)]):new Map}function kt(e){return e.storage.organizers}async function At(e){let t=[],n;do{let r=await kt(e).query({orderBy:{name:`asc`},limit:100,cursor:n});t.push(...r.items.map(e=>e.data)),r.hasMore&&(!r.cursor||t.length>=5e3)&&i(`Organizer list exceeds the supported scan limit or has an incomplete page.`),n=r.hasMore?r.cursor:void 0}while(n);return t}function jt(e,t){return t.length?kt(e).getMany([...new Set(t)]):Promise.resolve(new Map)}async function B(e){if(!e.schema||!e.content)return;let t=await L(e);return t&&!t.fields?.some(e=>e.slug===`start`)&&i(`Not an event schema.`),t}async function V(e,t,n=!1){let r=[],a,o=new Set;do{let s=await e.content.list(t,{limit:100,cursor:a,...n?{where:{status:`published`}}:{}});if(r.push(...s.items),r.length>dt)throw new ft(dt);if(!s.hasMore)break;(!s.cursor||o.has(s.cursor))&&i(`Invalid cursor.`),o.add(s.cursor),a=s.cursor}while(!0);return r}async function Mt(e,t){let n=await B(e);if(!n)return await Qe(e)||i(`Events are not connected to a content type. Turn on "Show old events saved inside the plugin".`),{native:!1,events:(await Et(e,{published:!0,...t?{through:t}:{}})).map(t=>t.locale?t:{...t,locale:e.site?.locale??`en`}),schema:n};let r=await V(e,n.slug,!0),a=[];for(let e of r){let t=He(e);t||i(`Invalid event: `+e.id),t.published&&a.push(t)}return{native:!0,events:a,schema:n}}async function Nt(e,t,n){let r=new Map,i=[...new Set(t.flatMap(e=>e.venueId?[e.venueId]:[]))],a=n?await Pt(e,I(n,`venue`),t,e=>e.venueId):await Ot(e,i);for(let[e,t]of a){let n=De(t);n&&r.set(e,n)}return r}async function Pt(e,t,n,r){let i=new Map;for(let e of n){let t=r(e);if(!t)continue;let n=i.get(t)??new Set;n.add((e.locale??``).toLowerCase()),i.set(t,n)}let a=new Map;if(!i.size||!e.content)return a;let o=await Ge(e,`directory:`+t,()=>V(e,t,!0)),s=new Map,c=new Map;for(let e of o){if(e.status!==`published`)continue;s.set(e.id,e);let t=e.translationGroup||e.id,n=(e.locale??``).toLowerCase();c.set(`${t}|${n}`,e)}for(let[e,t]of i){let n=s.get(e);if(n){a.set(e,n);for(let r of t){if(!r||r===(n.locale??``).toLowerCase())continue;let t=n.translationGroup||n.id,i=c.get(`${t}|${r}`);i&&a.set(`${e}|${r}`,i)}}}return a}function Ft(e,t,n=!1){let r=e=>Intl.getCanonicalLocales(e)[0].toLowerCase(),i=t?r(t):void 0,a=new Map;for(let t of e){let e=t.translationGroup??t.id,n=a.get(e)??[];n.push(t);for(let[e,r]of Object.entries(t.translations??{}))n.push({...t,...r,locale:e,descriptionBlocks:void 0,exceptions:t.exceptions.map(e=>({...e,overrides:e.overrides?Object.fromEntries(Object.entries(e.overrides).filter(([e])=>![`title`,`description`,`location`,`organizer`,`locale`].includes(e))):void 0}))});a.set(e,n)}let o=[];for(let t of a.values()){t.sort((e,t)=>(e.locale??``).localeCompare(t.locale??``)||e.id.localeCompare(t.id));let a=i?t.find(e=>e.locale&&r(e.locale)===i):t.find(t=>!t.translations||e.includes(t))??t[0];if(a)o.push(a);else if(!n){let n=t.find(t=>e.includes(t))??t[0],r=n.locale?`[`+n.locale.toUpperCase()+`] `:``;o.push({...n,title:r+n.title,exceptions:(n.exceptions??[]).map(e=>e.overrides?.title===void 0?e:{...e,overrides:{...e.overrides,title:r+e.overrides.title}})})}}return o}async function It(e,t,n=!0){let r=new Map,i=await L(e);if(t.some(e=>e.organizerId)){let n=I(i,`organizer_ref`);for(let[i,a]of await Pt(e,n,t,e=>e.organizerId))r.set(i,{id:a.id,name:String(a.data.name??a.data.title??``),website:E(String(a.data.website??``)),contactUrl:E(String(a.data.contact_url??a.data.contactUrl??``))})}let a=e.plugin?.id??`eventual`,o=new Map,s={};if(n&&i&&e.content?.getPublicUrl)for(let n of t){let t=n.id.split(`#`)[0],r=s[n.locale];if(!n.published||!n.slug||o.has(t))continue;let a=(i.urlPattern??`/`+i.slug+`/{slug}`).replace(`{slug}`,encodeURIComponent(n.slug)).replace(`{id}`,t).replace(/(.)\/$/,`$1`);if(r){o.set(t,r[0]+a+r[1]);continue}if(lt(e)<3)continue;let c=await Ge(e,`url:`+i.slug+`:`+t,()=>e.content.getPublicUrl(i.slug,t)),l=c?.replace(/\/$/,``);o.set(t,c),l?.endsWith(a)&&!a.includes(`{`)&&(s[n.locale]=[l.slice(0,-a.length),c.slice(l.length)])}return Promise.all(t.map(async e=>{let t=r.get((e.organizerId??``)+`|`+(e.locale??``).toLowerCase())??r.get(e.organizerId??``),n=o.get(e.id.split(`#`)[0])??e.publicUrl;return{...e,organizer:e.organizer||t?.name||e.organizerDetails?.name||``,organizerDetails:t??e.organizerDetails,publicUrl:n,imageUrl:e.featuredMediaId||e.imageMediaId?ze(a,e.id):e.imageUrl||``}}))}function Lt(e){let t=e=>({rule:null,error:e}),n=String(e.frequency||``).trim().toLowerCase();if(!n||n===`none`)return{rule:null};let r=String(e.until||``).trim();if(!p(r))return t(`Repeat until must be a valid YYYY-MM-DD date.`);let i=e.interval===void 0||String(e.interval).trim()===``?1:Number(e.interval);if(!Number.isInteger(i)||i<1||i>52)return t(`Interval must be an integer between 1 and 52.`);let a={frequency:n,until:r,...i>1?{interval:i}:{}};if(n===`weekly`&&e.weekdays){let n=Array.isArray(e.weekdays)?e.weekdays:String(e.weekdays).split(`,`).map(e=>e.trim());if(n.some(e=>!D.includes(e)))return t(`Choose valid weekdays.`);n.length&&(a.weekdays=te(n))}else if(n===`monthly`){let n=e.monthlyPatternType??`dayOfMonth`;if(n===`dayOfMonth`){let r=Number(e.dayOfMonth??1);if(!Number.isInteger(r)||r<1||r>31)return t(`Day of month must be between 1 and 31.`);a.pattern={type:n,dayOfMonth:r,missingDayBehavior:e.missingDayBehavior===`lastDay`?`lastDay`:`skip`}}else if(n===`weekdayOfMonth`){let r=String(e.weekday||`monday`).toLowerCase();if(!D.includes(r))return t(`Choose a valid weekday.`);let i=e.position===`last`?`last`:Number(e.position??1);if(i!==`last`&&(!Number.isInteger(i)||i<1||i>5))return t(`Choose first, second, third, fourth, fifth or last.`);a.pattern={type:n,weekday:r,position:i}}else return t(`Choose a monthly pattern.`)}return[`daily`,`weekly`,`monthly`].includes(n)?O(a)?{rule:a}:t(`Invalid `+n+` recurrence.`):t(`Unsupported recurrence frequency: `+n)}function Rt(e){if(e=P(e),!O(e))return{frequency:`none`,interval:1};let t={frequency:e.frequency,interval:e.interval??1,until:e.until};return e.frequency===`weekly`&&e.weekdays&&(t.weekdays=[...e.weekdays]),e.frequency===`monthly`&&e.pattern&&(e.pattern.type===`dayOfMonth`?(t.monthlyPatternType=`dayOfMonth`,t.dayOfMonth=e.pattern.dayOfMonth,t.missingDayBehavior=e.pattern.missingDayBehavior):(t.monthlyPatternType=`weekdayOfMonth`,t.weekday=e.pattern.weekday,t.position=e.pattern.position)),t}function zt(e){if(e=P(e),!O(e))return`Does not repeat`;let t=ee(e);if(e.frequency===`monthly`){let n=e.pattern;t+=n.type===`dayOfMonth`?` on day ${n.dayOfMonth} (${n.missingDayBehavior===`skip`?`skip missing months`:`use last day if missing`})`:` on ${n.position===`last`?`last`:[`first`,`second`,`third`,`fourth`,`fifth`][n.position-1]} ${n.weekday[0].toUpperCase()}${n.weekday.slice(1)}`}return`${t} through ${e.until}`}function Bt(e){let t=new Set([`title`,`description`,`excerpt`,`featured_image`,`image_url`,`start`,`end`,`start_date`,`end_date`,`all_day`,`timezone`,`location_type`,`venue`,`venue_id`,`location`,`virtual_url`,`external_url`,`organizer`,`organizer_ref`,`organizer_id`,`organizer_details`,`categories`,`recurrence`]),n=structuredClone(Object.fromEntries(Object.entries(e).filter(([e])=>t.has(e))));return n.event_status=`published`,n}function Vt(e,t,n){return{version:1,dependencies:[...new Set([e.slug,I(e,`venue`),I(e,`organizer_ref`),`emdash:settings`])],generatedAt:new Date(t).toISOString(),expiresAt:new Date(Math.min(t+15e3,n?(Math.floor(t/864e5)+1)*864e5:1/0)).toISOString()}}function Ht(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function Ut(e,t){try{return await Wt(e,R(t))}catch(e){if(e instanceof at)return{ok:!1,error:`SANDBOX_BUDGET_EXCEEDED`,details:e.message,events:void 0};throw e}}async function Wt(e,t){let n={ok:!1,error:`INVALID_QUERY`};if(!Ht(e)||[`from`,`through`,`category`,`locale`,`eventId`].some(t=>e[t]!==void 0&&typeof e[t]!=`string`)||[e.strict,e.publicUrls].some(e=>![void 0,!0,!1,`true`,`false`].includes(e)))return n;try{e.locale&&Intl.getCanonicalLocales(e.locale)}catch{return n}let r=typeof e.eventId==`string`&&e.eventId.trim()?e.eventId.trim():void 0,i=Date.now(),a=new Date(i).toISOString().slice(0,10),o=e.from??a,s=e.through??m(o,180);if(!p(o)||!p(s)||o>s)return{ok:!1,error:`INVALID_DATE_RANGE`};if((Date.parse(`${s}T00:00:00Z`)-Date.parse(`${o}T00:00:00Z`))/864e5+1>366)return{ok:!1,error:`DATE_RANGE_TOO_LARGE`,maxDays:366};let c,l;try{if(l=await Mt(t,s),c=Ft(l.events,e.locale,[!0,`true`].includes(e.strict)),r){let e=r.split(`#`)[0];c=c.filter(t=>t.id===e)}}catch(e){if(e instanceof ft)return{ok:!1,error:`EVENT_LIMIT_EXCEEDED`,maxEvents:e.limit};throw e}let u=M(c,o,s),d=e.category?x(e.category):``,f=d?u.filter(e=>e.categories.some(e=>x(e)===d)):u;if(r&&r.includes(`#`)&&(f=f.filter(e=>e.id===r)),f.length>1e4)return{ok:!1,error:`OCCURRENCE_LIMIT_EXCEEDED`};if(l.native){let[n,r]=await Promise.all([Nt(t,f,l.schema),It(t,f,[void 0,!0,`true`].includes(e.publicUrls))]);return{ok:!0,from:o,through:s,cache:Vt(l.schema,i,e.from===void 0),events:r.map(e=>Ue(e,n,t.site.url,t.plugin.id))}}let[h,g]=await Promise.all([Ot(t,f.flatMap(e=>e.venueId?[e.venueId]:[])),jt(t,f.flatMap(e=>e.organizerId?[e.organizerId]:[]))]);return{ok:!0,from:o,through:s,events:f.map(e=>Be(e,e.venueId?h.get(e.venueId):void 0,t.plugin.id,e.organizerId?g.get(e.organizerId):void 0))}}async function Gt(e,t,n){let r=e,a=await B(t);if(!a)return{blocks:[{type:`context`,text:`Choose an event collection in Event settings.`}]};let o=(e,n)=>({type:`link`,label:n,target:{kind:`external`,url:new URL(e,t.site.url).href}}),s=`/_emdash/admin/content/`+encodeURIComponent(a.slug);if(r.page===`widget:upcoming-events`)return{blocks:[{type:`header`,text:`Upcoming events`},...((await Ut({},t)).events??[]).slice(0,5).map(e=>({type:`section`,block_id:`eventual-verbatim`,text:e.title+` · `+e.start}))]};let c=[{type:`header`,text:`Events`},{type:`context`,text:`Create and edit announcements in EmDash. Save first, then open the Dates, venue & repeat panel.`}];if(r.action_id===`duplicate-event`){(!n||typeof r.value!=`string`)&&i(`Sign in before creating a copy.`);let e=await t.content.get(a.slug,r.value);e||i(`This event no longer exists.`);let l=Bt((e.draftRevisionId?await t.content.getRevision?.(a.slug,e.id,e.draftRevisionId):void 0)?.data??e.data),u=new Set(a.fields.filter(e=>!e.validation?.relation).map(e=>e.slug)),d=await t.content.create(a.slug,Object.fromEntries(Object.entries({...l,title:String(l.title??`Event`)+` (copy)`}).filter(([e])=>u.has(e))),{locale:e.locale??void 0});c.push({type:`context`,text:`Draft copy created.`},{type:`actions`,elements:[o(s+`/`+encodeURIComponent(d.id),`Edit the copy`)]})}else r.action_id&&!String(r.action_id).startsWith(`page-native-events`)&&i(`Reload the workspace before trying this action.`);let l=await F(t);c.push({type:`actions`,elements:[o(s+`/new`,`Create event`),o(s,`All events`),...[`venue`,`organizer_ref`].flatMap(e=>{let t=I(a,e);return l.some(e=>e.slug===t)?[o(`/_emdash/admin/content/`+encodeURIComponent(t),e===`venue`?`Manage venues`:`Manage organizers`)]:[]})]});let u=String(r.action_id).startsWith(`page-native-events`)?String(r.value||``):void 0,d=await t.content.list(a.slug,{limit:20,cursor:u});c.push({type:`table`,page_action_id:`page-native-events`,columns:[{key:`title`,label:`Event`},{key:`locale`,label:`Language`},{key:`status`,label:`Publication`,format:`badge`},{key:`edit`,label:`Edit`,format:`element`},...n?[{key:`copy`,label:`Copy`,format:`element`}]:[]],rows:d.items.map(e=>({title:String(e.data.title||e.slug),locale:e.locale??``,status:e.status,edit:o(s+`/`+encodeURIComponent(e.id),`Edit`),...n?{copy:{type:`button`,action_id:`duplicate-event`,label:`Duplicate`,value:e.id}}:{}})),empty_text:`No events yet.`}),d.hasMore&&(!d.cursor||d.cursor===u)&&i(`Incomplete event page. Reload the workspace.`);let f=[...u?[{type:`button`,action_id:`page-native-events-first`,label:`First page`,value:``}]:[],...d.hasMore?[{type:`button`,action_id:`page-native-events-next`,label:`Next events`,value:d.cursor}]:[]];return f.length&&c.push({type:`actions`,elements:f}),c.push({type:`header`,text:`Subscribe`},{type:`actions`,elements:[o(`/_emdash/api/plugins/eventual/calendar`,`Calendar subscription (.ics)`),o(`/_emdash/api/plugins/eventual/publicEvents`,`Published events (JSON)`)]}),{blocks:c}}const Kt=e=>({type:`context`,text:e}),qt=()=>({type:`actions`,elements:[[`/events`,`Events`],[`/venues`,`Venues`],[`/organizers`,`Organizers`],[`/settings`,`Settings`]].map(([e,t])=>({type:`button`,action_id:`open-page:`+e,label:t,value:e}))}),Jt=(e,t,n)=>({type:`actions`,elements:[{type:`link`,label:n,target:{kind:`external`,url:new URL(`/_emdash/admin/content/`+encodeURIComponent(t),e.site.url).href}}]});async function Yt(e,t){let n=await Ze(e),r=await Qe(e),i=await F(e),a=i.find(e=>e.slug===`events`),o=(e,t)=>String(a?.fields.find(t=>t.slug===e)?.options?.collection??t),s=(e,t)=>({type:`select`,action_id:e,label:t,options:[{value:``,label:e===`events`?`Choose a collection`:`No collection`},...i.map(e=>({value:e.slug,label:(e.label||e.slug)+` (`+e.slug+`)`}))],initial_value:n?.[e]??(e===`events`?a?.slug??``:i.some(t=>t.slug===o(e===`venues`?`venue`:`organizer_ref`,e))?o(e===`venues`?`venue`:`organizer_ref`,e):``)});return{blocks:[qt(),{type:`header`,text:`Settings`},Kt(`Choose content types.`),...t?[{type:`banner`,title:`Settings not saved`,description:t,variant:`error`}]:[],{type:`form`,block_id:`collection-settings:`+Object.values(n??{}).join(`:`),fields:[s(`events`,`Event collection`),s(`venues`,`Venue collection`),s(`organizers`,`Organizer collection`)],submit:{action_id:`save-settings`,label:`Save settings`}},{type:`form`,block_id:`legacy-reads:`+r,fields:[{type:`toggle`,action_id:`legacyReads`,label:`Show old events saved inside the plugin`,description:`Enable to serve old plugin events.`,initial_value:r}],submit:{action_id:`save-legacy-reads`,label:`Save switch`}},{type:`actions`,elements:[{type:`link`,label:`Setup guide`,target:{kind:`external`,url:`https://github.com/Vermeulen-Solutions/eventual-rsvp-core`}}]}]}}async function Xt(e,t,n){t=R(t);let r=e&&typeof e==`object`&&!Array.isArray(e)?{...e}:{};if(r.type===`form_submit`&&(!r.values||typeof r.values!=`object`||Array.isArray(r.values)))return{blocks:[{type:`banner`,title:`Invalid admin request`,variant:`error`}]};String(r.action_id??``).startsWith(`open-page:`)&&(r.type=`page_load`,r.page=r.value,delete r.action_id);let a=r.page;if(a===`/settings`||r.action_id===`save-settings`||r.action_id===`save-legacy-reads`){if(!n||n.role<50)return{blocks:[qt(),Kt(`Only an administrator can change these settings.`)]};if(r.action_id===`save-legacy-reads`)try{let e=r.values?.legacyReads;e===!0||e===!1||e===`true`||e===`false`||i(`The legacy read setting must be on or off.`),await $e(t,e===!0||e===`true`)}catch(e){return Yt(t,e instanceof Error?e.message:`Check the legacy read setting.`)}if(r.action_id===`save-settings`)try{let e=r.values;(!e||e.defaultTimezone!==void 0&&!h(String(e.defaultTimezone)))&&i(`Choose a valid IANA time zone.`),await nt(t,{events:String(e.events??``),venues:String(e.venues??``),organizers:String(e.organizers??``)}),e.defaultTimezone!==void 0&&await t.settings.set(`defaultTimezone`,String(e.defaultTimezone))}catch(e){return Yt(t,e instanceof Error?e.message:`Check the collection settings.`)}return Yt(t)}try{let e=await et(t);if(!e.schema){let e=await Qe(t);return{blocks:[qt(),{type:`header`,text:`Connect events to a content type`},Kt(`Choose an event content type.`),Kt(e?`Public calendars show old plugin events.`:`Turn on "Show old events saved inside the plugin" in settings if needed.`),Kt(`You can copy the old events into a content type. See the setup guide.`)]}}if(a===`/venues`||a===`/organizers`){let n=a===`/venues`?e.venues:e.organizers;return{blocks:[qt(),Kt(`Create and edit these entries in the EmDash content editor.`),...n?[Jt(t,n,a===`/venues`?`Manage venues`:`Manage organizers`)]:[Kt(`No collection selected. Ask an administrator to configure it in Event settings.`)]]}}return{blocks:[qt(),...(await Gt(r,t,n)).blocks]}}catch(e){return{blocks:[qt(),{type:`banner`,title:`Review collection settings`,description:e instanceof Error?e.message:`Collections could not be loaded.`,variant:`error`}]}}}const Zt=new Set([`label`,`text`,`title`,`description`,`placeholder`,`empty_text`,`confirm`,`deny`,`message`]),Qt=new Set([`venueId`,`organizerId`,`venue`,`organizer_ref`,`imageMediaId`,`timezone`,`eventIds`,`events`,`venues`,`organizers`]);function $t(e,t){let n=e=>{if(Array.isArray(e))return e.map(n);if(!e||typeof e!=`object`)return e;let r=e;return String(r.block_id).startsWith(`eventual-verbatim`)?r:Object.fromEntries(Object.entries(r).map(([e,i])=>[`value`,`initial_value`,`target`,`condition`,`patch`].includes(e)?[e,i]:e===`options`&&Qt.has(String(r.action_id))?[e,i.map(e=>e.value===``?{...e,label:t(e.label)}:e)]:e===`rows`?[e,i.map(e=>Object.fromEntries(Object.entries(e).map(([e,i])=>{if(typeof i!=`string`)return[e,n(i)];let a=i[0]?.toUpperCase()+i.slice(1),o=r.columns.some(t=>t.key==e&&t.format==`badge`)?t(a):e==`effective`?t(i):i;return[e,o==a?i:o]})))]:e===`label`&&r.action_id===`edit-organizer`?[e,i]:[e,Zt.has(e)&&typeof i==`string`?t(i):n(i)]))};return n(e)}const en=new Map;function tn(e){let t=0,n=(n,r)=>{let a=[],o=``,s=()=>{o&&a.push(o),o=``};for(;t<e.length;){let c=e[t];if(c===`{`)s(),t++,a.push(i(n));else if(c===`}`&&r)break;else c===`#`&&n?(s(),a.push(0),t++):(o+=c,t++)}return s(),a},r=()=>{for(;e[t]===` `;)t++;let n=t;for(;t<e.length&&!/[\s,{}]/.test(e[t]);)t++;let r=e.slice(n,t);for(;e[t]===` `||e[t]===`
12
12
  `;)t++;return r},i=i=>{let a=r();if(e[t]===`}`)return t++,{a};t++;let o=r();if(o!==`plural`&&o!==`select`){let n=e[t]===`,`?(t++,r()):``;for(;t<e.length&&e[t]!==`}`;)t++;return t++,{a,t:o,s:n}}t++;let s={};for(;;){let a=r();if(!a||e[t]!==`{`)break;t++,s[a]=n(o===`plural`||i,!0),t++}for(;t<e.length&&e[t]!==`}`;)t++;return t++,{a,p:o===`plural`,o:s}};return n(!1,!1)}function nn(e,t,n,r){let i=``;for(let a of e)if(typeof a==`string`)i+=a;else if(a===0)i+=r===void 0?`#`:new Intl.NumberFormat(n).format(r);else if(a.t)i+=rn(a,t[a.a],n);else if(!a.o)i+=a.a in t?String(t[a.a]):`{${a.a}}`;else{let e=t[a.a],o;if(a.p){let r=Number(e),s=`other`;try{s=new Intl.PluralRules(n).select(r)}catch{}o=a.o[`=`+r]??a.o[s]??a.o.other,i+=nn(o??[],t,n,r)}else o=a.o[String(e)]??a.o.other,i+=nn(o??[],t,n,r)}return i}function rn(e,t,n){if(t==null||t===``)return``;try{if(e.t===`number`)return new Intl.NumberFormat(n).format(Number(t));if(e.t===`date`){let r=String(t),i=new Date(/^\d{4}-\d{2}-\d{2}$/.test(r)?r+`T00:00:00Z`:r);return Number.isNaN(i.getTime())?r:new Intl.DateTimeFormat(n,{dateStyle:e.s||`medium`,...r.length===10?{timeZone:`UTC`}:{}}).format(i)}}catch{}return String(t)}function an(e,t={},n=`en`){if(!e.includes(`{`))return e;let r=en.get(e);return r||(r=tn(e),en.size>4e3&&en.clear(),en.set(e,r)),nn(r,t,n)}const on=[`fr`,`de`,`nl`,`es`,`it`,`pt`,`pt-BR`,`pl`,`cs`,`sv`,`da`,`nb`,`fi`,`ja`,`zh-CN`,`ko`,`tr`,`uk`,`ar`,`he`],sn={no:`nb`,nn:`nb`,iw:`he`,"zh-Hans":`zh-CN`,"zh-SG":`zh-CN`,"zh-MY":`zh-CN`};function cn(e,t=on){let n;try{n=Intl.getCanonicalLocales(String(e||``).trim().replace(/_/g,`-`))[0]}catch{}if(!n)return`en`;let[r,...i]=n.split(`-`),a=i.find(e=>e.length===4),o=i.find(e=>e.length===2||/^\d{3}$/.test(e)),s=[];if(r===`zh`){if(a===`Hant`||!a&&[`TW`,`HK`,`MO`].includes(o))return`en`;s.push(`zh-CN`)}o&&s.push(`${r}-${o}`,sn[`${r}-${o}`]),a&&s.push(sn[`${r}-${a}`]),s.push(r,sn[r]);for(let e of s)if(e===`en`||t.includes(e))return e;return`en`}const ln=new WeakMap;function un(e,t=`en`){if(!e)return e=>e;let n=ln.get(e);if(!n){n=[];for(let t of Object.keys(e)){if(!/\{\w+\}/.test(t))continue;let e=[],r=t.split(/(\{\w+\})/).map(t=>{let n=/^\{(\w+)\}$/.exec(t)?.[1];return n?(e.push(n),`([\\s\\S]+?)`):t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}).join(``);n.push([RegExp(`^${r}$`),e,t])}ln.set(e,n)}let r=(r,o)=>{if(typeof r!=`string`||!r)return r;let s=e[r];if(s)return s.includes(`{`)?an(s,{},t):s;let c=null;for(let[t,i,a]of n){let n=e[a]&&t.exec(r);n&&(!c||n[n.length-1].length<c[0][c[0].length-1].length)&&(c=[n,i,a])}if(c){let[n,r,s]=c,l={};r.forEach((e,t)=>{let r=n[t+1],o=a(r);o===r&&r.includes(`, `)&&(o=i(r.split(`, `).map(a))),l[e]=o});let u=an(e[s],l,t);return o?u:u.charAt(0).toLocaleUpperCase(t)+u.slice(1)}return r},i=e=>{try{return new Intl.ListFormat(t).format(e)}catch{return e.join(`, `)}},a=t=>{let n=t&&t[0].toLowerCase()+t.slice(1);return n!==t&&e[n]?e[n]:r(t,!0)};return e=>r(e,!1)}const dn=new Map;function fn(e,t){return`https://cdn.jsdelivr.net/npm/${e.package}@${e.version}/catalogs/${e.namespace}/${t}.json`}const pn=(e,t)=>`i18n:${e.namespace}:${e.version}:${t}`;async function mn(e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t,0,16))).slice(0,22)}async function hn(e,t,n){let r=await e.http.fetch(fn(t,n));if(!r.ok)return null;let i=await r.text();if(await mn(i)!==t.hashes[n])return null;let a=JSON.parse(i);return!a||typeof a!=`object`?null:(await e.kv.set(pn(t,n),a),dn.set(pn(t,n),{messages:a}),a)}async function gn(e,t,n,r){let i=cn(n,Object.keys(t.hashes));if(i===`en`)return null;let a=pn(t,i),o=dn.get(a);if(o&&(o.messages||Date.now()<o.retry))return o.messages;let s=null;try{if(r&&r()<1)return null;if(s=await e.kv?.get(a)??null,!s){if(!e.http||!e.kv||r&&r()<2)return null;s=await hn(e,t,i)}}catch{s=null}return s&&typeof s!=`object`&&(s=null),dn.set(a,s?{messages:s}:{messages:null,retry:Date.now()+3e5}),s}var _n={package:`@vermeulen.solutions/eventual-locales`,version:`0.1.10`,namespace:`core`,hashes:{ar:`Jr+SsiJppqn2rr/WpJigRw`,cs:`BbmJhujNUiL8fDBw/+wCSw`,da:`Ij9IaV5B7gd+am4YKMcedw`,de:`ADmFQCy+Pv3q6PQSBk7xKQ`,es:`cr3OI43MX3EWALXbjnsy8w`,fi:`OLwpZx/szCaR5fcj8oeMaA`,fr:`FeirW6Y9C44xXOyGFL92hA`,he:`tKYZPpsv0f3z/Ms4/Tm7Lw`,it:`0NiDiE62pLdaGfmXKRcxGA`,ja:`rQsLMNECmEpjxZjz7Wrrww`,ko:`Wx1hBxDHnVUVZ/0hdbvJjA`,nb:`EirSx4KtSzX4NeN+TbK1aw`,nl:`XvvsZpZE2RpqMAPV8bENeg`,pl:`AK0ph74u6zSkAiTlsQX8bg`,"pt-BR":`D2Gp1nCw+85dT6fYcnQK4A`,pt:`c4JysqbI2mVcHXwlQn//XA`,sv:`fTU5PPBSLJJfkW20fY6Nlg`,tr:`uH3GpUPNIN9znD3hNVxTFw`,uk:`jnSPOMPPXXq2RvcLB9c6LQ`,"zh-CN":`ltuv2/7aXv+T0FZFFWIyAQ`}};async function vn(e,t){let n=R(e),r=await gn(n,_n,t,()=>lt(n));return r?un(r,t):null}async function yn(e){await gn(e,_n,e.site?.locale)}function bn(e,t){return p(e)&&p(t)&&e<=t&&Date.parse(`${t}T00:00:00Z`)-Date.parse(`${e}T00:00:00Z`)<366*864e5}function xn(e,t){return t.allDay?e:_(e,t.timezone)}function Sn(e,t,n,r=100,a=0){(!bn(t,n)||!Number.isInteger(r)||r<1||r>100||!Number.isInteger(a)||a<0)&&i(`Invalid occurrence range or limit.`);let o=M([{...e,exceptions:e.exceptions.filter(e=>e.status!==`cancelled`)}],t,n),s=o.slice(a,a+r).map(t=>{let n=e.recurrence?t.id.slice(e.id.length+1):null,r=n?j(e,n):e,i=e.exceptions.find(e=>e.recurrenceId===n);return{id:t.id,recurrenceId:n,scheduledStart:r.start,scheduledEnd:r.end,scheduledLocalStart:xn(r.start,r),scheduledLocalEnd:xn(r.end,r),scheduledTimezone:r.timezone,start:t.start,end:t.end,localStart:xn(t.start,t),localEnd:xn(t.end,t),timezone:t.timezone,allDay:t.allDay,status:i?.status??`scheduled`}});return{from:t,through:n,occurrences:s,total:o.length,truncated:a+s.length<o.length}}function Cn(e,t,n,r=10,a=0){bn(t,n)||i(`Invalid occurrence date range. Must be <= 366 days.`);let o=P(e.recurrence);if(!o||typeof o!=`object`)return{from:t,through:n,occurrences:[],total:0,offset:a,limit:r,hasMore:!1};let s=!!e.all_day,c=String(e.timezone||`Europe/Zurich`),l=s?String(e.start_date||``):String(e.start||``),u=s?String(e.end_date||l):String(e.end||l),d=P(e.exceptions),f=Array.isArray(d)?d:[],p=new Map;for(let e of f)e&&typeof e.recurrenceId==`string`&&p.set(e.recurrenceId,e);let m=P(e.occurrence_content),h=new Map((Array.isArray(m)?m:[]).map(e=>[e.recurrenceId,e.overrides])),g={id:`series`,title:String(e.title||``),description:``,start:l,end:u,allDay:s,timezone:c,location:``,organizer:``,externalUrl:``,imageUrl:``,categories:[],published:!0,recurrence:o,exceptions:[],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},v=Se(g,t,n).map(e=>{let t=e.id.slice(7),n=j(g,t)??e,r=p.get(t),i=r?.status===`cancelled`,a=r?.status===`modified`,o=i?`cancelled`:a?`modified`:`scheduled`,l=a&&r?.overrides?{...e,...r.overrides}:e,u=(e,t,n)=>t?e:_(e,n);return{id:t,recurrenceId:t,scheduledStart:n.start,scheduledEnd:n.end,scheduledLocalStart:u(n.start,s,c),scheduledLocalEnd:u(n.end,s,c),effectiveStart:i?n.start:l.start,effectiveEnd:i?n.end:l.end,effectiveLocalStart:u(i?n.start:l.start,l.allDay,l.timezone||c),effectiveLocalEnd:u(i?n.end:l.end,l.allDay,l.timezone||c),timezone:l.timezone||c,allDay:l.allDay,status:o,hasLocalizedCopy:h.has(t),localizedCopy:h.get(t)}});return{from:t,through:n,occurrences:v.slice(a,a+r),total:v.length,offset:a,limit:r,hasMore:a+r<v.length}}function wn(e=[],t){let n=e.filter(e=>e.recurrenceId!==t);return n.push({recurrenceId:t,status:`cancelled`}),n}function Tn(e=[],t,n){let r=e.filter(e=>e.recurrenceId!==t);return r.push({recurrenceId:t,status:`modified`,overrides:n}),r}function En(e=[],t){return e.filter(e=>e.recurrenceId!==t)}function Dn(e=[],t,n){return[...e.filter(e=>e.recurrenceId!==t),{recurrenceId:t,overrides:{...e.find(e=>e.recurrenceId===t)?.overrides,...n}}]}function On(e=[],t){return e.filter(e=>e.recurrenceId!==t)}function kn(e,t,n,r=``,i=!1,a=80){let o=new Map;for(let t of e){let e=t.translationGroup||t.id;o.has(e)||o.set(e,[]),o.get(e).push(t)}let s=[...o.values()].map(e=>{let r=[...e].sort((e,t)=>Number(t.status===`published`)-Number(e.status===`published`)||e.id.localeCompare(t.id)),a=r.find(e=>e.id===n)??r[0],o=r.find(e=>e.status===`published`&&e.locale?.toLowerCase()===t.toLowerCase())??r.find(e=>e.status===`published`)??r.find(e=>e.locale?.toLowerCase()===t.toLowerCase())??r[0],s=i?De(o):void 0,c=String(o.data.name??o.data.title??o.id),l=s?.address??``;return{value:a.id,editId:o.id,label:c+(l?` — `+l:``)+` [`+(o.locale||`default`).toUpperCase()+`]`+(a.status===`published`?``:` (publish before the event)`),name:c,address:l,published:a.status===`published`}}).sort((e,t)=>e.label.localeCompare(t.label)),c=r.trim().normalize(`NFD`).replace(/\p{M}/gu,``).toLowerCase(),l=s.filter(e=>!c||e.label.normalize(`NFD`).replace(/\p{M}/gu,``).toLowerCase().includes(c)),u=l.slice(0,a),d=s.find(e=>e.value===n);return d&&!u.includes(d)&&u.push(d),{choices:u,current:d,matches:l.length}}const An=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:{};[...D.slice(1),D[0]].map(e=>({value:e,label:e[0].toUpperCase()+e.slice(1)}));const jn=(e,t,n)=>({type:`date_input`,action_id:e,label:t,initial_value:a(n)||void 0}),Mn=(e,t,n,r=!1)=>({type:`text_input`,action_id:e,label:t,initial_value:a(n),multiline:r}),Nn=(e,t,n,r)=>({type:`combobox`,action_id:e,label:t,options:n,initial_value:a(r)}),Pn=(e,t,n)=>({type:`form`,block_id:e,fields:n,submit:{action_id:e,label:t}}),Fn=e=>P(e.exceptions)??[],In=e=>P(e.occurrence_content)??[],H=e=>({type:`editor-draft-patch`,operations:e}),U=(e,t)=>({op:`set`,field:e,value:t}),Ln=e=>({op:`clear`,field:e});function Rn(e,t,n){let r=a(e);try{return t?r:r&&Number.isFinite(Date.parse(r))?_(r,n):r}catch{return r}}function zn(e){let t=!!e.all_day,n=a(e.timezone)||`Europe/Zurich`;return{allDay:t,timezone:n,start:Rn(t?e.start_date:e.start,t,n),end:Rn(t?e.end_date:e.end,t,n)}}function Bn(e,t=``,n){let r=zn(e);return[{type:`toggle`,action_id:t+`all_day`,label:`All-day event`,initial_value:r.allDay},jn(t+`start_date`,`Start date`,r.start.slice(0,10)),{...Mn(t+`start_time`,`Start time`,r.start.slice(11,16)),placeholder:`18:30`,condition:{field:t+`all_day`,eq:!1}},jn(t+`end_date`,`End date (last day for all-day events)`,r.end.slice(0,10)),{...Mn(t+`end_time`,`End time`,r.end.slice(11,16)),placeholder:`20:00`,condition:{field:t+`all_day`,eq:!1}},Nn(t+`timezone`,`Time zone`,[...new Set([r.timezone,`UTC`,`Europe/Zurich`,`Europe/Paris`,`Europe/London`,`America/New_York`])].map(e=>({value:e,label:e.replaceAll(`_`,` `)})).concat({value:`custom`,label:`Other time zone…`}),r.timezone),{...Mn(t+`custom_timezone`,`Other IANA time zone`),placeholder:`Pacific/Auckland`,condition:{field:t+`timezone`,eq:`custom`}}].map(e=>n&&Object.hasOwn(n,e.action_id)?{...e,initial_value:n[e.action_id]}:e)}function Vn(e,t=``){let n=e[t+`all_day`]===!0,r=a(e[t+`timezone`]===`custom`?e[t+`custom_timezone`]:e[t+`timezone`]).trim(),o=a(e[t+`start_date`]),s=a(e[t+`end_date`])||o;if((!p(o)||!p(s))&&i(`Choose a valid start and end date.`),n)return{all_day:!0,timezone:r,start_date:o,end_date:s};let c=g(o+`T`+a(e[t+`start_time`]),r),l=g(s+`T`+a(e[t+`end_time`]),r);return(!c.value||!l.value)&&i(c.error||l.error||`Enter times as HH:MM.`),{all_day:!1,timezone:r,start:c.value,end:l.value}}async function Hn(e,t){let n=e.ui?.entry;if(!n||n.collection!==(await L(t))?.slug&&n.collection!==`events`)return{blocks:[{type:`banner`,variant:`error`,title:`Open this panel from an event editor.`}]};let r=An(e.input),o=An(An(r.draft).fields);if(!r.draft){let e=await t.content?.get(n.collection,n.id);if(o=e?.data??{},e?.draftRevisionId){let r=await t.content?.getRevision?.(n.collection,n.id,e.draftRevisionId);r&&(o=r.data)}}try{o={...o,recurrence:P(o.recurrence),exceptions:P(o.exceptions),occurrence_content:P(o.occurrence_content)}}catch{return{blocks:[{type:`banner`,variant:`error`,title:`Stored event data needs repair`,description:`The recurrence or date overrides could not be read.`}]}}let s=An(r.values),c,l,u=a(r.value)||a(s.recurrence_id),d=0,f;try{r.type!==`panel_load`&&!r.draft&&i(`Reload the editor before changing this event.`);let e=a(r.action_id);if(e===`apply-recurrence`){let e=a(s.frequency),t=Lt(e.startsWith(`monthly-`)?{...s,frequency:`monthly`,monthlyPatternType:e===`monthly-weekday`?`weekdayOfMonth`:`dayOfMonth`,interval:Number((e===`monthly-weekday`?s.interval_months_weekday:s.interval_months)??s.interval??1)}:{...s,interval:Number(s[`interval_`+(e===`daily`?`days`:`weeks`)]??s.interval??1)});t.error&&i(t.error),c=H(t.rule?[U(`recurrence`,t.rule)]:[Ln(`recurrence`)])}else if(e===`apply-schedule`){let e=Vn(s);c=H([...Object.entries(e).map(([e,t])=>U(e,t)),...e.all_day?[Ln(`start`),Ln(`end`)]:[Ln(`start_date`),Ln(`end_date`)]])}else if(e===`apply-details`){let e=await L(t);for(let n of[`venue`,`organizer_ref`].filter(e=>Object.hasOwn(s,e))){e&&!e.fields.some(t=>t.slug===it(e,n))&&i(`Upgrade event reference schema first.`);let r=a(s[n]);r&&!await t.content?.get(I(e,n),r)&&i(`Selected entry no longer exists.`)}c=H([...[`venue`,`organizer_ref`].filter(e=>Object.hasOwn(s,e)).map(t=>U(it(e,t),a(s[t])))])}else if(e!==`search-directories`)if(e===`page-occurrences`){let e=An(JSON.parse(a(r.value)||`{}`));d=Math.max(0,Math.min(500,Number(e.offset)||0)),f=a(e.from)}else if(e===`inspect-window`)f=a(s.from),u=``;else if([`cancel-occurrence`,`restore-occurrence`,`reschedule-occurrence`,`set-occurrence-copy`,`clear-occurrence-copy`,`edit-occurrence`].includes(e)){let t=Fe(o,{allowStaleOccurrenceCopy:!0}),r=j({id:n.id,start:t.all_day?t.start_date:t.start,end:t.all_day?t.end_date:t.end,allDay:t.all_day,timezone:t.timezone,recurrence:P(o.recurrence)},u);if(r||i(`Date no longer belongs to repeat schedule.`),f=Rn(r.start,r.allDay,r.timezone).slice(0,10),e===`cancel-occurrence`&&(c=H([U(`exceptions`,wn(Fn(o),u))])),e===`restore-occurrence`&&(c=H([U(`exceptions`,En(Fn(o),u))])),e===`clear-occurrence-copy`&&(c=H([U(`occurrence_content`,On(In(o),u))])),e===`reschedule-occurrence`){let e=Vn(s,`override_`);c=H([U(`exceptions`,Tn(Fn(o),u,{start:a(e.all_day?e.start_date:e.start),end:a(e.all_day?e.end_date:e.end),allDay:e.all_day,timezone:e.timezone}))])}if(e===`set-occurrence-copy`){let e={};for(let t of[`title`,`location`,`organizer`])s[`use_`+t]===!0&&(e[t]=a(s[`copy_`+t]));if(s.use_description===!0){let t=In(o).find(e=>e.recurrenceId===u)?.overrides.description;e.description=t!==void 0&&N(t)===a(s.copy_description)?t:Te(a(s.copy_description))}let t=In(o).filter(e=>e.recurrenceId!==u);c=H([U(`occurrence_content`,Object.keys(e).length?Dn(t,u,e):t)])}}else e&&i(`Unknown action. Reload the panel.`);if(c){let t={...o};for(let e of c.operations)t[e.field]=e.op===`clear`?null:e.value;(e!==`apply-details`||[`start`,`end`,`start_date`,`end_date`].some(e=>t[e]))&&Fe(t,{allowStaleOccurrenceCopy:!0}),c.operations=c.operations.filter(e=>{let t=o[e.field];if(e.op===`clear`)return t!=null&&t!==``;let n=t;if(typeof t==`string`&&(Array.isArray(e.value)||typeof e.value==`object`))try{n=JSON.parse(t)}catch{}return JSON.stringify(n??``)!==JSON.stringify(e.value)}),o=t,c.operations.length||(c=void 0)}}catch(e){l=e instanceof Error?e.message:`Changes could not be applied.`,c=void 0}return{fields:o,effect:c,state:{selectedId:u,offset:d,windowStart:f,search:a(s.directory_search),values:l?s:void 0,locale:n.locale??``,uiLocale:e.ui?.locale||`en`,error:l,action:a(r.action_id),origin:t.site?.url||new URL(e.request.url).origin}}}const Un=(e,t,n=``,r=!1)=>({type:`text_input`,action_id:e,label:t,initial_value:String(n??``),multiline:r}),Wn=(e,t,n,r)=>({type:`select`,action_id:e,label:t,options:n,initial_value:String(r??``)}),Gn=(e,t,n)=>({type:`date_input`,action_id:e,label:t,initial_value:String(n??``)}),W=(e,t,n)=>({type:`button`,action_id:e,label:t,value:n}),Kn=(e,t,n=!1)=>({type:`accordion`,label:e,blocks:t,default_open:n});async function qn(e,t,n){let r=[];n.error&&r.push({type:`banner`,title:`Check these details`,description:n.error,variant:`error`}),r.push(Kn(`When`,[Pn(`apply-schedule`,`Save dates to draft`,Bn(e,``,n.values))],!0));let i=Rt(e.recurrence),a={...i,...n.values},o=i.frequency===`monthly`?i.monthlyPatternType===`weekdayOfMonth`?`monthly-weekday`:`monthly-day`:i.frequency,s=[...D.slice(1),D[0]].map(e=>({value:e,label:e[0].toUpperCase()+e.slice(1)})),c=[Wn(`frequency`,`Repeat`,[{value:`none`,label:`Does not repeat`},{value:`daily`,label:`Daily`},{value:`weekly`,label:`Weekly`},{value:`monthly-day`,label:`Monthly — day of month`},{value:`monthly-weekday`,label:`Monthly — weekday position`}],a.frequency===`monthly`?o:a.frequency)];for(let[e,t,n]of[[`daily`,`days`,`Every … days`],[`weekly`,`weeks`,`Every … weeks`],[`monthly-day`,`months`,`Every … months`],[`monthly-weekday`,`months_weekday`,`Every … months`]])c.push({type:`number_input`,action_id:`interval_`+t,label:n,initial_value:Number(a[`interval_`+t]??a.interval??1),min:1,max:52,condition:{field:`frequency`,eq:e}});c.push({...Gn(`until`,`Last repeat date`,a.until),condition:{field:`frequency`,neq:`none`}},{type:`checkbox`,action_id:`weekdays`,label:`Days of the week`,options:s,initial_value:Array.isArray(a.weekdays)?a.weekdays:[],condition:{field:`frequency`,eq:`weekly`}},{type:`number_input`,action_id:`dayOfMonth`,label:`Day of month`,initial_value:Number(a.dayOfMonth??(String(e.start_date??e.start??``).slice(8,10)||1)),min:1,max:31,condition:{field:`frequency`,eq:`monthly-day`}},{...Wn(`missingDayBehavior`,`When this day does not exist`,[{value:`skip`,label:`Skip that month`},{value:`lastDay`,label:`Use the month’s last day`}],a.missingDayBehavior??`skip`),condition:{field:`frequency`,eq:`monthly-day`}},{...Wn(`weekday`,`Weekday`,s,a.weekday??`monday`),condition:{field:`frequency`,eq:`monthly-weekday`}},{...Wn(`position`,`Weekday position`,[1,2,3,4,5,`last`].map((e,t)=>({value:String(e),label:[`First`,`Second`,`Third`,`Fourth`,`Fifth`,`Last`][t]})),a.position??1),condition:{field:`frequency`,eq:`monthly-weekday`}}),r.push(Kn(`Repeat`,[{type:`context`,text:zt(e.recurrence)},Pn(`apply-recurrence`,`Save repeat settings`,c)],n.action===`apply-recurrence`));let l=await L(t),u=[];for(let[r,i]of[[`venue`,`Saved venue`],[`organizer_ref`,`Saved organizer`]]){let a=it(l,r);if(!l?.fields.some(e=>e.slug===a))continue;let o=I(l,r),s=rt(e[a]),c=kn((await F(t)).some(e=>e.slug===o)?await V(t,o):[],n.locale,s,void 0,r===`venue`,998).choices;u.push({type:`combobox`,action_id:r,label:i,options:[{value:``,label:r===`venue`?`No saved venue`:`No saved organizer`},...c],initial_value:s??``})}r.push(Kn(`Where`,[Pn(`apply-details`,`Save venue and organizer`,u)],n.action===`apply-details`));try{Fe(e,{allowStaleOccurrenceCopy:!0});let t=new Date().toISOString().slice(0,10),i=String(e.start_date??e.start??``).slice(0,10),a=n.windowStart??(i>t?i:t),o=A(a,89),s=Cn(e,a,o,20,n.offset),c=[Pn(`inspect-window`,`Show dates`,[Gn(`from`,`Show dates from`,a)]),{type:`context`,text:a+` — `+o}];for(let e of s.occurrences)c.push({type:`section`,block_id:`eventual-verbatim:`+e.recurrenceId,text:e.scheduledLocalStart+` → `+e.scheduledLocalEnd+` · `+e.status},{type:`actions`,elements:[W(`edit-occurrence`,`Change date`,e.recurrenceId),...e.status===`cancelled`?[W(`restore-occurrence`,`Restore date`,e.recurrenceId)]:[W(`cancel-occurrence`,`Cancel date`,e.recurrenceId)],...e.status===`modified`?[W(`restore-occurrence`,`Restore date`,e.recurrenceId)]:[]]});let l=[];n.offset&&l.push(W(`page-occurrences-prev`,`Previous dates`,JSON.stringify({from:a,offset:Math.max(0,n.offset-20)}))),s.hasMore&&l.push(W(`page-occurrences-next`,`Next dates`,JSON.stringify({from:a,offset:n.offset+20}))),l.length&&c.push({type:`actions`,elements:l}),c.push({type:`actions`,elements:[W(`window-prev`,`Previous 90 days`,A(a,-90)),W(`window-next`,`Next 90 days`,A(a,90))]});let u=s.occurrences.find(e=>e.recurrenceId===n.selectedId);if(u){let t=Wn(`recurrence_id`,`Occurrence`,[{value:u.recurrenceId,label:u.scheduledLocalStart}],u.recurrenceId),r={...e,all_day:u.allDay,timezone:u.timezone,...u.allDay?{start_date:u.effectiveStart,end_date:u.effectiveEnd}:{start:u.effectiveStart,end:u.effectiveEnd}};c.push(Pn(`reschedule-occurrence`,`Save changed date`,[t,...Bn(r,`override_`,n.values)]));let i=u.localizedCopy??{};c.push(Pn(`set-occurrence-copy`,`Save announcement for this date`,[t,...[`title`,`description`,`location`,`organizer`].flatMap(e=>[{type:`toggle`,action_id:`use_`+e,label:`Use a different `+e,initial_value:i[e]!==void 0},{...Un(`copy_`+e,e[0].toUpperCase()+e.slice(1),e===`description`?N(i[e]):i[e],e===`description`),condition:{field:`use_`+e,eq:!0}}])]),{type:`actions`,elements:[W(`clear-occurrence-copy`,`Use the series announcement`,u.recurrenceId)]})}r.push(Kn(`Individual dates`,c,!!n.selectedId))}catch(e){r.push(Kn(`Individual dates`,[{type:`context`,text:e instanceof Error?e.message:`Check the event schedule.`}]))}return{blocks:r}}const Jn=e=>JSON.stringify([e.updatedAt,e.draftRevisionId??``,e.status]),Yn=e=>({blocks:[{type:`banner`,title:e,variant:`error`}]});async function Xn(e,t){t=R(t);let n=await L(t),r=e.ui?.entry;if(!n||r?.collection!==n.slug)return{blocks:[{type:`context`,text:`Eventual RSVP manages the collection chosen in Event settings.`}]};let i=await t.content?.get(n.slug,r.id);if(!i)return Yn(`This event no longer exists.`);let a=(i.draftRevisionId?await t.content?.getRevision?.(n.slug,i.id,i.draftRevisionId):void 0)?.data??i.data,o=e.input&&typeof e.input==`object`?e.input:{},[s,c]=String(o.action_id??``).split(`|`);if(o.type!==`panel_load`&&c!==encodeURIComponent(Jn(i)))return Yn(`This event changed. Close and reopen the panel before trying again.`);s?.startsWith(`page-occurrences-`)&&(s=`page-occurrences`),s?.startsWith(`window-`)&&(s=`inspect-window`,o.values={from:o.value});let l=await Hn({...e,input:{...o,action_id:s,draft:{fields:a}}},t);if(`blocks`in l)return l;let u=l.effect?.operations;if(u?.length){let e=await t.content.get(n.slug,i.id);if(!e||Jn(e)!==Jn(i))return Yn(`This event changed. Close and reopen the panel before trying again.`);let r=new Set(n.fields.filter(e=>!e.validation?.relation).map(e=>e.slug)),a={};for(let e of u){if(!r.has(e.field)||[`title`,`description`,`excerpt`].includes(e.field))return Yn(`The event schema needs an administrator to review this field.`);a[e.field]=e.op===`clear`?null:e.value}return await t.content.update(n.slug,i.id,a),{blocks:[{type:`context`,text:`Schedule saved as an EmDash draft. Publish in the content editor when ready.`}],refresh:!0,toast:{message:`Schedule draft saved.`,type:`success`}}}let d=encodeURIComponent(Jn(i)),f=e=>{if(Array.isArray(e))return e.map(f);if(!e||typeof e!=`object`)return e;let t=e;return Object.fromEntries(Object.entries(t).map(([e,n])=>[e,e===`action_id`&&(t.type===`button`||!t.type&&`label`in t)?String(n)+`|`+d:f(n)]))},p=await qn(l.fields,t,l.state);return p.blocks=f(p.blocks),p.blocks.unshift({type:`context`,text:`Save announcement edits first. This panel updates the saved draft. Publish in core. Dates and venue are shared across languages.`}),p}const Zn=(t,n)=>e({status:t,headers:{"content-type":`text/plain; charset=utf-8`},body:{kind:`text`,value:n}}),Qn=()=>Zn(404,`Not found`);async function $n(t,n){if(n=R(n),typeof t!=`object`||!t||Array.isArray(t))return Qn();let r=t.eventId;if(typeof r!=`string`||r.length<1||r.length>128)return Qn();let[i,a]=r.split(`#`),o=await B(n),s=o?await n.content.get(o.slug,i):void 0;if(o&&!s&&o.fields.some(e=>e.slug===`legacy_id`&&e.indexed)){let e=await n.content.list(o.slug,{limit:2,where:{status:`published`,fieldFilters:{legacy_id:i}}});if(e.hasMore||e.items.length>1)return Qn();s=e.items[0]}let c=!o&&await Qe(n),l=o?He(s):c?await z(n,r)??await z(n,i):void 0;if(l&&a){let e=l.exceptions?.find(e=>e.recurrenceId===a),t=e?.overrides?.featuredMediaId||e?.overrides?.imageMediaId;t&&(l={...l,featuredMediaId:t,imageMediaId:t})}let u=l?.featuredMediaId||l?.imageMediaId;if(!l?.published||!u||!n.media?.readBytes)return Qn();let d=await n.media.get(u);if(!d||!Re(d.mimeType))return Qn();if(d.size!==null&&d.size>Le)return Zn(413,`Event image is too large`);try{let t=await n.media.readBytes(u,{maxBytes:Le});return!Re(t.mimeType)||t.mimeType!==d.mimeType?Qn():e({status:200,headers:{"content-type":t.mimeType,"cache-control":`public, max-age=3600, must-revalidate`},body:{kind:`bytes`,value:t.bytes}})}catch{return Qn()}}function er(e,t,n,r=new Date,a){let o=new Set(e.map(e=>G(e,n))),s=new Map;for(let e of t){let t=G(e,n),r=s.get(t);!o.has(t)&&(!r||e.cancelledAt>r.cancelledAt)&&s.set(t,e)}let c=`${[`BEGIN:VCALENDAR`,`VERSION:2.0`,`PRODID:-//Vermeulen Solutions//Eventual RSVP//EN`,`CALSCALE:GREGORIAN`,`METHOD:PUBLISH`,`X-WR-CALNAME:${K(a||`Eventual RSVP`)}`,...e.flatMap(e=>nr(e,n,r)),...[...s.values()].flatMap(e=>rr(e,n,r)),`END:VCALENDAR`].flatMap(lr).join(`\r
13
13
  `)}\r\n`;return tr.encode(c).length>4*1024*1024&&i(`Calendar output exceeds 4 MiB; narrow the subscription.`),c}const tr=new TextEncoder;function nr(e,t,n){let r=or(e.updatedAt)??n,i=`STATUS:${Me(e)}`,a=Ae(e),o=je({...e,externalUrl:e.publicUrl||e.externalUrl}),s=N(e.description);return[`BEGIN:VEVENT`,`UID:${K(G(e,t))}`,`DTSTAMP:${sr(n)}`,`LAST-MODIFIED:${sr(r)}`,`SEQUENCE:${ar(e.calendarSequence,r)}`,i,`SUMMARY:${K(e.title)}`,...s?[`DESCRIPTION:${K(s)}`]:[],...a?[`LOCATION:${K(a)}`]:[],...o?[`URL:${o}`]:[],...e.categories.length?[`CATEGORIES:${e.categories.map(K).join(`,`)}`]:[],`X-EVENTUAL-TIMEZONE:${K(e.timezone)}`,...ir(e.start,e.end,e.allDay),`END:VEVENT`]}function rr(e,t,n){let r=or(e.cancelledAt)??n;return[`BEGIN:VEVENT`,`UID:${K(G(e,t))}`,`DTSTAMP:${sr(n)}`,`LAST-MODIFIED:${sr(r)}`,`SEQUENCE:${ar(e.calendarSequence,r)}`,`STATUS:CANCELLED`,`SUMMARY:Cancelled event`,`X-EVENTUAL-TIMEZONE:${K(e.timezone)}`,...ir(e.start,e.end,e.allDay),`END:VEVENT`]}function ir(e,t,n){if(n){let n=cr(t.slice(0,10));return[`DTSTART;VALUE=DATE:${e.slice(0,10).replaceAll(`-`,``)}`,`DTEND;VALUE=DATE:${n.replaceAll(`-`,``)}`]}let r=or(e),i=or(t);return r&&i?[`DTSTART:${sr(r)}`,...i>r?[`DTEND:${sr(i)}`]:[]]:[]}function G(e,t){let n=typeof e==`string`?e:e.id;typeof e!=`string`&&e.id.startsWith(`cancellation_`)&&e.eventId&&(n=e.eventId);let r=typeof e==`string`?void 0:e.translationGroup,a=n;if(r){let e=n.indexOf(`#`);a=`eventual-${r}${e>=0?n.slice(e):``}`}let o=t.trim().replace(/[^a-zA-Z0-9.-]/g,`-`).toLowerCase()||`eventual.invalid`;if(typeof e!=`string`&&e.calendarUid){let t=e.calendarUid.lastIndexOf(`@`);(t<1||/[\r\n\u0000-\u0020]/.test(e.calendarUid))&&i(`Invalid stored calendar UID.`);let r=n.includes(`#`)?encodeURIComponent(n.slice(n.indexOf(`#`))):``;return e.calendarUid.slice(0,t)+r+e.calendarUid.slice(t)}return`${encodeURIComponent(a)}@${o}`}function ar(e,t){let n=e??Math.floor(t.getTime()/1e3);return Math.min(2147483647,Math.max(0,Math.floor(n)))}function K(e){return e.replace(/\\/g,`\\\\`).replace(/\r\n|\r|\n/g,`\\n`).replace(/,/g,`\\,`).replace(/;/g,`\\;`).replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g,``)}function or(e){let t=Date.parse(e);return Number.isFinite(t)?new Date(t):void 0}function sr(e){return e.toISOString().replace(/[-:]/g,``).replace(/\.\d{3}Z$/,`Z`)}function cr(e){let t=new Date(`${e}T00:00:00Z`);return!/^\d{4}-\d{2}-\d{2}$/.test(e)||!Number.isFinite(t.getTime())?e:(t.setUTCDate(t.getUTCDate()+1),t.toISOString().slice(0,10))}function lr(e){let t=[],n=``,r=0;for(let i of e){let e=tr.encode(i).length;r+e>75&&(t.push(n),n=` `,r=1),n+=i,r+=e}return t.push(n),t}const ur=`state:eventual-calendar-snapshot`,dr=new WeakMap;function fr(e,t=`eventual.invalid`){try{return new URL(e.site.url).host}catch{return t}}function pr(e,t=`eventual.invalid`){let n=dr.get(e);if(n)return n;let r=mr(e,t);return dr.set(e,r),r}async function mr(e,t){let n=await e.kv.get(ur);if(n?.version===1&&n.host)return n.host;let r=await e.kv.get(`state:eventual-calendar-host`);if(r)return r;let i=fr(e,t);return(await e.kv.compareAndSet(`state:eventual-calendar-host`,null,i)).applied?i:await e.kv.get(`state:eventual-calendar-host`)}async function hr(e){let t=new Date,n=t.toISOString().slice(0,10),r=new Date(t);r.setUTCDate(r.getUTCDate()+365);let a=r.toISOString().slice(0,10),o=await e.kv.getVersioned(ur);o&&o.value.version!==1&&i(`Unsupported calendar snapshot.`);let s=o?[]:await e.kv.list(`state:eventual-calendar`),c=s.find(e=>e.key===`state:eventual-calendar-lock`)?.value;c&&c.until>Date.now()&&i(`Calendar busy; retry.`);let l=o?.value.host??s.find(e=>e.key===`state:eventual-calendar-host`)?.value;l||=fr(e),dr.set(e,Promise.resolve(l));let u=new Map(o?Object.entries(o.value.groups):s.filter(e=>e.key.startsWith(`state:eventual-calendar:`)).map(e=>[decodeURIComponent(e.key.slice(24)),e.value]));u.size>1e4&&i(`Calendar state limit exceeded.`);let d=new Map(u),f=!o,p=ct(e,1);try{let r=await Mt(e);if(!r.native)return{events:r.events,cancellations:[]};r.events=await It(e,r.events,!1);let s=await Nt(e,r.events,r.schema),c=new Map;for(let e of r.events){let t=e.translationGroup??e.id,n=c.get(t)??[];n.push(e),c.set(t,n)}let m=new Set([...c.keys(),...u.keys()]),h=[],g=[],_=0;for(let o of m){let p=(c.get(o)??[]).sort((e,t)=>e.id.localeCompare(t.id)),m=JSON.stringify([e.site,r.schema?.urlPattern,r.schema?.routable,p.map(e=>({...e,calendarSequence:void 0,venue:Ee(s,e)}))]),v=u.get(o);if(v?.fingerprint===m&&v.from===n){_+=v.occurrences.length,_>1e4&&i(`Calendar occurrence limit exceeded.`),g.push(...p.map(e=>({...e,calendarSequence:v.sequence}))),h.push(...v.cancellations),h.length>1e4&&i(`Calendar cancellation limit exceeded.`);continue}let y=v?.fingerprint!==m,b=v?v.sequence+(y?1:0):p.some(e=>e.calendarUid)?Math.floor(t.getTime()/1e3):0;b>2147483647&&i(`Calendar sequence exhausted.`);let S=M(p.slice(0,1),n,a);S.length>1e3&&i(`Calendar occurrence limit exceeded.`),_+=S.length,_>1e4&&i(`Calendar occurrence limit exceeded.`);let C=new Set(S.map(e=>G(e,l))),w=new Map(S.map(e=>[G(e,l),e.categories.map(x)])),T=[...new Set(p.flatMap(e=>e.locale?[e.locale.toLowerCase()]:[]))],E=(v?.cancellations??[]).filter(e=>Date.parse(e.cancelledAt)>t.getTime()-366*864e5&&(e.feedCategory?!w.get(G(e,l))?.includes(e.feedCategory):e.locale?!T.includes(e.locale):!C.has(G(e,l))));for(let e of v?.occurrences??[])if(!C.has(G(e,l))&&e.end.slice(0,10)>=n&&E.push({...e,cancelledAt:t.toISOString(),calendarSequence:b}),C.has(G(e,l)))for(let n of e.categories??[])w.get(G(e,l))?.includes(x(n))||E.push({...e,feedCategory:x(n),cancelledAt:t.toISOString(),calendarSequence:b});for(let e of v?.locales??[])if(!T.includes(e))for(let n of v?.occurrences??[])C.has(G(n,l))&&E.push({...n,locale:e,cancelledAt:t.toISOString(),calendarSequence:b});let D=[...new Map(E.map(e=>[G(e,l)+`:`+(e.locale??``)+`:`+(e.feedCategory??``),e])).values()];D.length>1e3&&i(`Cancellation history limit exceeded for this series.`);let O={from:n,locales:T,fingerprint:m,sequence:b,occurrences:S.map(e=>({id:e.id,eventId:e.id,start:e.start,end:e.end,allDay:e.allDay,timezone:e.timezone,translationGroup:e.translationGroup,calendarUid:e.calendarUid,calendarSequence:b,cancelledAt:t.toISOString(),categories:e.categories,locales:T})),cancellations:D};d.set(o,O),f=!0,g.push(...p.map(e=>({...e,calendarSequence:b}))),h.push(...D),h.length>1e4&&i(`Calendar cancellation limit exceeded.`)}let v={version:1,host:l,groups:Object.fromEntries(d)};return new TextEncoder().encode(JSON.stringify(v)).length>1024*1024&&i(`Calendar snapshot exceeds 1 MiB.`),p(),f&&((await e.kv.compareAndSet(ur,o?.revision??null,v)).applied||i(`Calendar state conflict; retry.`)),{events:g,cancellations:h,venues:s,host:l}}finally{p()}}async function gr(e,t,n){e=R(e);let r=new Date().toISOString().slice(0,10),a=new Date(r+`T00:00:00Z`);a.setUTCDate(a.getUTCDate()+365);let o=a.toISOString().slice(0,10),s=await B(e),c=s?{native:!0,schema:s,events:[]}:await Mt(e,o),l=c.native?await hr(e):{events:c.events,cancellations:[]},u=M(Ft(l.events,n?.locale,n?.strict),r,o);u.length>1e4&&i(`Too many calendar occurrences.`);let d=n?.category?x(n.category):``,f=d?u.filter(e=>e.categories.some(e=>x(e)===d)):u,p=`venues`in l&&l.venues||await Nt(e,f,c.schema),m=(c.native?await It(e,f):f).map(e=>({...e,location:Ue(e,p).location})),h=e.storage?.calendar_cancellations?await xt(e):[];return er(m,[...l.cancellations,...h].filter(e=>Date.parse(e.cancelledAt)>Date.now()-366*864e5&&(!d||e.categories?.some(e=>x(e)===d))&&(!e.feedCategory||e.feedCategory===d)&&(e.locale?n?.strict&&n.locale?.toLowerCase()===e.locale:!n?.strict||!n.locale||!e.locales||e.locales.includes(n.locale.toLowerCase()))),`host`in l&&l.host||await pr(e,t),void 0,n?.calendarName)}const q=(e,t)=>({type:`object`,properties:e,...t&&t.length>0?{required:t}:{},additionalProperties:!1}),J=(e=0,t=12e3)=>({type:`string`,...e>0?{minLength:e}:{},maxLength:t}),_r={type:`string`},Y=(e,t)=>({type:`integer`,...e===void 0?{}:{minimum:e},...t===void 0?{}:{maximum:t}}),vr={type:`boolean`},X=e=>({type:`string`,enum:e}),yr=(e,t,n)=>({type:`array`,items:e,...t===void 0?{}:{maxItems:t},...n===void 0?{}:{minItems:n}}),br=X([`sunday`,`monday`,`tuesday`,`wednesday`,`thursday`,`friday`,`saturday`]),xr={oneOf:[q({frequency:{type:`string`,const:`daily`},until:_r,interval:Y(1,52)},[`frequency`,`until`]),q({frequency:{type:`string`,const:`weekly`},until:_r,interval:Y(1,52),weekdays:yr(br,7,1)},[`frequency`,`until`]),q({frequency:{type:`string`,const:`monthly`},until:_r,interval:Y(1,52),pattern:{oneOf:[q({type:{type:`string`,const:`dayOfMonth`},dayOfMonth:Y(1,31),missingDayBehavior:X([`skip`,`lastDay`])},[`type`,`dayOfMonth`,`missingDayBehavior`]),q({type:{type:`string`,const:`weekdayOfMonth`},weekday:br,position:{anyOf:[{type:`number`,const:1},{type:`number`,const:2},{type:`number`,const:3},{type:`number`,const:4},{type:`number`,const:5},{type:`string`,const:`last`}]}},[`type`,`weekday`,`position`])]}},[`frequency`,`until`,`pattern`])]},Sr=X([`physical`,`virtual`,`hybrid`]),Cr=X([`draft`,`published`,`cancelled`,`postponed`,`rescheduled`]),wr=yr(J(0,100),30),Tr={title:J(1,200),description:J(0,12e3),start:J(1,32),end:J(1,32),allDay:vr,timezone:J(1,100),location:J(0,500),locationType:Sr,virtualUrl:J(0,2048),status:Cr,organizer:J(0,300),organizerId:J(0,200),externalUrl:J(0,2048),imageUrl:J(0,2048),imageMediaId:J(0,200),categories:wr,venueId:J(0,200),recurrence:xr},Er=q({id:J(1,200)},[`id`]),Dr=q(Tr,[`title`,`start`,`end`,`allDay`]),Or=q({...Tr,recurrence:{anyOf:[xr,{type:`null`}]}}),kr={name:J(1,200),street:J(0,300),street2:J(0,300),locality:J(0,150),region:J(0,150),postalCode:J(0,40),country:J(0,100)},Ar=q(kr,[`name`]),jr=q({id:J(1,200)},[`id`]),Mr=q(kr),Nr=q({id:J(1,200),patch:Or},[`id`,`patch`]),Pr=q({id:J(1,200),patch:Mr},[`id`,`patch`]),Fr=q({locationType:Sr,virtualUrl:J(0,2048),status:Cr,title:J(1,200),description:J(0,12e3),start:J(1,32),end:J(1,32),allDay:vr,timezone:J(1,100),location:J(0,500),organizer:J(0,300),externalUrl:J(0,2048),imageUrl:J(0,2048),categories:wr}),Ir=q({eventId:J(1,200),recurrenceId:J(0,16),status:X([`cancelled`,`modified`]),overrides:Fr},[`eventId`,`recurrenceId`,`status`]),Lr=q({eventId:J(1,200),recurrenceId:J(0,16)},[`eventId`,`recurrenceId`]),Rr=q({}),zr=q({from:_r,through:_r,includeDrafts:vr,limit:Y(1,100)}),Br=q({id:J(1,200),from:_r,through:_r,limit:Y(1,100)},[`id`]),Vr=q({defaultTimezone:J(1,100),collections:q({events:J(1,63),venues:J(0,63),organizers:J(0,63)},[`events`,`venues`,`organizers`]),legacyReads:vr},[`defaultTimezone`]),Hr={name:J(1,200),website:J(0,2048),contactUrl:J(0,2048)},Ur=q(Hr,[`name`]),Wr=q({id:J(1,200),expectedUpdatedAt:J(1,32),patch:q(Hr)},[`id`,`expectedUpdatedAt`,`patch`]),Gr={id:J(1,200),createdAt:J(1,32),updatedAt:J(1,32)},Kr=q({start:J(1,32),end:J(1,32),allDay:vr,timezone:J(1,100),changedAt:J(1,32)},[`start`,`end`,`allDay`,`timezone`,`changedAt`]),qr=q({recurrenceId:J(1,16),status:X([`cancelled`,`modified`]),overrides:q({...Fr.properties,imageMediaId:J(0,200)})},[`recurrenceId`,`status`]),Jr={events:q({...Tr,...Gr,calendarSequence:Y(0,2147483647),calendarUid:J(1,500),locale:J(1,40),translations:{type:`object`,maxProperties:20,additionalProperties:q({title:J(1,500),description:J(0,1e4),location:J(0,500),organizer:J(0,500)},[`title`,`description`,`location`,`organizer`])},published:vr,exceptions:yr(qr,500),scheduleHistory:yr(Kr,10),previousStartDate:J(1,32)},[`id`,`title`,`description`,`start`,`end`,`allDay`,`timezone`,`location`,`organizer`,`externalUrl`,`imageUrl`,`categories`,`published`,`exceptions`,`createdAt`,`updatedAt`]),venues:q({...kr,...Gr},Object.keys({...kr,...Gr})),organizers:q({...Hr,...Gr},Object.keys({...Hr,...Gr}))},Yr=q({collection:X([`events`,`venues`,`organizers`]),source:J(1,200),mode:X([`copy`,`restore`]),records:yr(q({sourceId:J(1,200),data:{type:`object`,additionalProperties:!0}},[`sourceId`,`data`]),10,1)},[`collection`,`source`,`records`]),Xr={listEvents:zr,getEvent:Er,listOccurrences:Br,createEvent:Dr,updateEvent:Nr,publishEvent:Er,unpublishEvent:Er,deleteEvent:Er,setOccurrenceException:Ir,removeOccurrenceException:Lr,listVenues:Rr,createVenue:Ar,updateVenue:Pr,deleteVenue:jr,getSettings:Rr,updateSettings:Vr,listOrganizers:Rr,createOrganizer:Ur,updateOrganizer:Wr,previewImport:Yr,importRecords:Yr,exportRecords:q({collection:X([`events`,`venues`,`organizers`]),cursor:J(1,2e3),limit:Y(1,10)},[`collection`]),migrateToNative:q({locale:J(1,20),venueCollection:J(1,100),dryRun:vr,cursor:J(1,4e3),limit:Y(1,100),venueMapping:{type:`object`,additionalProperties:J(1,200),maxProperties:1e3}})};function Zr(e,t){if(e.anyOf)return e.anyOf.some(e=>Zr(e,t));if(e.oneOf)return e.oneOf.filter(e=>Zr(e,t)).length===1;if(`const`in e&&t!==e.const||e.enum&&!e.enum.some(e=>e===t))return!1;switch(e.type){case`null`:return t===null;case`boolean`:return typeof t==`boolean`;case`number`:case`integer`:return typeof t==`number`&&Number.isFinite(t)&&(e.type!==`integer`||Number.isInteger(t))&&(e.minimum===void 0||t>=Number(e.minimum))&&(e.maximum===void 0||t<=Number(e.maximum));case`string`:return typeof t==`string`&&t.length>=Number(e.minLength??0)&&t.length<=Number(e.maxLength??1/0);case`array`:return Array.isArray(t)&&t.length>=Number(e.minItems??0)&&t.length<=Number(e.maxItems??1/0)&&t.every(t=>!!e.items&&Zr(e.items,t));case`object`:{if(!t||typeof t!=`object`||Array.isArray(t))return!1;let n=t;if(e.maxProperties!==void 0&&Object.keys(n).length>e.maxProperties)return!1;let r=e.properties;return r?(e.required??[]).every(e=>Object.hasOwn(n,e)&&n[e]!==void 0)&&Object.keys(n).every(e=>Object.hasOwn(r,e)&&(n[e]===void 0||Zr(r[e],n[e]))):e.additionalProperties===!0||typeof e.additionalProperties==`object`&&Object.values(n).every(t=>Zr(e.additionalProperties,t))}default:return!1}}function Qr(e,t){if(!Zr(Xr[e],t))return!1;let n=t;if([`listEvents`,`listOccurrences`].includes(e)&&[n.from,n.through].some(e=>e!==void 0&&!p(e)))return!1;let r=e===`createEvent`?n:e===`updateEvent`?n.patch:void 0;return!(r?.recurrence!=null&&!O(r.recurrence))}function $r(e,t){if(!Zr(Jr[e],t))return!1;if(e===`events`){let e=t;try{let t=Object.keys(e.translations??{});return(!e.locale||Intl.getCanonicalLocales(e.locale)[0]===e.locale)&&t.every(t=>Intl.getCanonicalLocales(t)[0]===t&&t.toLowerCase()!==e.locale?.toLowerCase())}catch{return!1}}return!0}const ei={title:``,description:``,start:``,end:``,allDay:!1,timezone:`UTC`,location:``,locationType:`physical`,virtualUrl:``,status:`draft`,organizer:``,externalUrl:``,imageUrl:``,imageMediaId:``,categories:``,venueId:``,published:!1,repeatFrequency:`none`,recurrenceUntil:``,recurrenceInterval:1,monthlyPattern:`dayOfMonth`,missingDayBehavior:`skip`,monthlyWeekday:`monday`,monthlyPosition:1,exceptions:[]};async function ti(e,t){let n=await e.media?.get(t);if(!n||!Re(n.mimeType))return!1;if(n.size!==null)return n.size<=Le;if(!e.media?.readBytes)return!1;try{let r=await e.media.readBytes(t,{maxBytes:Le});return r.mimeType===n.mimeType&&Re(r.mimeType)&&r.bytes.byteLength<=Le}catch{return!1}}async function ni(e,t,n,r){let i={name:t.name.trim(),website:t.website?.trim()??``,contactUrl:t.contactUrl?.trim()??``};if(!i.name||i.name.length>200||[i.website,i.contactUrl].some(e=>e.length>2048||e&&!E(e)))return{ok:!1,error:`Use a name and valid public HTTP(S) URLs.`};let a=kt(e),o=n?await a.getVersioned(n):null;if(n&&(!o||o.value.updatedAt!==r))return{ok:!1,error:`This organizer changed. Reload before saving.`};let s=_t(o?.value.updatedAt),c={...i,website:E(i.website),contactUrl:E(i.contactUrl),id:n??crypto.randomUUID(),createdAt:o?.value.createdAt??s,updatedAt:s};return(await a.compareAndSet(c.id,o?.revision??null,c)).applied?{ok:!0,organizer:c}:{ok:!1,error:`This organizer changed. Reload before saving.`}}const Z=()=>({ok:!1,error:`NOT_FOUND`});function Q(e,t,n=!1){return{permission:`plugins:manage`,handler:async(r,i)=>(n&&(i=R(i)),Qr(e,r.input)?!n&&await B(i)?{ok:!1,error:`NATIVE_COLLECTIONS_ACTIVE`,details:`Use EmDash content tools.`}:t(r.input,i):{ok:!1,error:`VALIDATION_ERROR`})}}function ri(e,t){let n=t?ue(t):ei,r=e.recurrence===null?void 0:e.recurrence??t?.recurrence;return{...n,title:e.title??n.title,description:e.description??n.description,start:e.start??n.start,end:e.end??n.end,allDay:e.allDay??n.allDay,timezone:e.timezone??n.timezone,location:e.location??n.location,locationType:e.locationType??n.locationType??`physical`,virtualUrl:e.virtualUrl??n.virtualUrl??``,status:e.status??n.status??(n.published?`published`:`draft`),organizer:e.organizer??n.organizer,organizerId:e.organizerId??n.organizerId,externalUrl:e.externalUrl??n.externalUrl,imageUrl:e.imageUrl??n.imageUrl,categories:e.categories?e.categories.join(`, `):n.categories,venueId:e.venueId??n.venueId,imageMediaId:e.imageMediaId??n.imageMediaId,repeatFrequency:r?.frequency??`none`,recurrenceUntil:r?.until??``,recurrenceInterval:r?.interval??1,weeklyWeekdays:r?.frequency===`weekly`?r.weekdays:void 0,monthlyDayOfMonth:r?.frequency===`monthly`&&r.pattern.type===`dayOfMonth`?r.pattern.dayOfMonth:void 0,monthlyPattern:r?.frequency===`monthly`?r.pattern.type:`dayOfMonth`,missingDayBehavior:r?.frequency===`monthly`&&r.pattern.type===`dayOfMonth`?r.pattern.missingDayBehavior:`skip`,monthlyWeekday:r?.frequency===`monthly`&&r.pattern.type===`weekdayOfMonth`?r.pattern.weekday:`monday`,monthlyPosition:r?.frequency===`monthly`&&r.pattern.type===`weekdayOfMonth`?r.pattern.position:1}}function $(e){return{ok:!1,error:`INVALID_EVENT`,details:[e]}}async function ii(e,t,n){let i=ri(t,n),a=le(i);if(!a.data)return $(a.error??`Check the event fields.`);if(a.data.externalUrl&&!E(a.data.externalUrl))return $(r);if(i.imageMediaId&&!await ti(e,i.imageMediaId))return $(`Choose a ready JPEG, PNG, GIF, WebP, or AVIF media image under 8 MiB.`);if(i.venueId&&!await St(e,i.venueId))return $(`The selected saved venue does not exist.`);if(i.organizerId&&!await kt(e).get(i.organizerId))return $(`The selected saved organizer does not exist.`);let o=new Date().toISOString(),s={...n,...a.data,recurrence:a.data.recurrence,venueId:a.data.venueId,organizerId:a.data.organizerId,imageMediaId:a.data.imageMediaId,virtualUrl:a.data.virtualUrl,locale:n?.locale??e.site.locale??`en`,id:n?.id??crypto.randomUUID(),exceptions:n?.exceptions??[],createdAt:n?.createdAt??o,updatedAt:o};for(let e of[`recurrence`,`venueId`,`organizerId`,`imageMediaId`,`virtualUrl`])s[e]===void 0&&delete s[e];return Ce(s)?{ok:!0,event:await gt(e,s)}:$(`Changing this schedule would invalidate occurrence exceptions. Remove or update those exceptions first.`)}function ai(e,t){let n=new Date().toISOString();return{name:e.name.trim(),street:e.street?.trim()??``,street2:e.street2?.trim()??``,locality:e.locality?.trim()??``,region:e.region?.trim()??``,postalCode:e.postalCode?.trim()??``,country:e.country?.trim()??``,id:t?.id??crypto.randomUUID(),createdAt:t?.createdAt??n,updatedAt:n}}const oi={"mcp/organizers/list":Q(`listOrganizers`,async(e,t)=>{let n=await B(t);if(n){let e=I(n,`organizer_ref`);return(await F(t)).some(t=>t.slug===e)?{ok:!0,organizers:(await V(t,e)).map(e=>({id:e.id,name:String(e.data.name??e.data.title??e.id),website:String(e.data.website??``),contactUrl:String(e.data.contact_url??``),locale:e.locale,status:e.status}))}:{ok:!0,organizers:[]}}return{ok:!0,organizers:await At(t)}},!0),"mcp/organizers/create":Q(`createOrganizer`,async(e,t)=>ni(t,e)),"mcp/organizers/update":Q(`updateOrganizer`,async(e,t)=>{let n=await kt(t).get(e.id);return n?ni(t,{...n,...e.patch},e.id,e.expectedUpdatedAt):Z()}),"mcp/events/list":Q(`listEvents`,async(e,t)=>{let n=new Date().toISOString().slice(0,10),r=e.from??n,i=e.through??m(r,180);if(r>i||Date.parse(`${i}T00:00:00Z`)-Date.parse(`${r}T00:00:00Z`)>365*864e5)return{ok:!1,error:`INVALID_DATE_RANGE`};let a=await B(t);if(a){let n=(await V(t,a.slug)).map(He).filter(e=>e!==null);return{ok:!0,from:r,through:i,events:M(e.includeDrafts?n:n.filter(e=>e.published),r,i).slice(0,e.limit??50)}}let o;try{o=await Et(t,{published:e.includeDrafts?void 0:!0})}catch(e){if(e instanceof ft)return{ok:!1,error:`EVENT_LIMIT_EXCEEDED`,maxEvents:e.limit};throw e}let s=M(o,r,i).slice(0,e.limit??50),c=await Ot(t,s.flatMap(e=>e.venueId?[e.venueId]:[]));return{ok:!0,from:r,through:i,events:s.map(e=>({...e,venue:e.venueId?c.get(e.venueId)??null:null}))}},!0),"mcp/events/get":Q(`getEvent`,async({id:e},t)=>{let n=await B(t);if(n){let r=await t.content?.get(n.slug,e);if(!r)return Z();let i=He(r);if(!i)return Z();let a=await B(t),o=await Nt(t,[i],a);return{ok:!0,event:(await It(t,[i]))[0],venue:Ee(o,i)??null}}let r=await z(t,e);return r?{ok:!0,event:r,venue:r.venueId?await St(t,r.venueId):null}:Z()},!0),"mcp/events/occurrences":Q(`listOccurrences`,async(e,t)=>{let n=e.from??new Date().toISOString().slice(0,10),r=e.through??m(n,89);if(!bn(n,r))return{ok:!1,error:`INVALID_DATE_RANGE`};let i=await B(t);if(i){let a=await t.content?.get(i.slug,e.id);if(!a)return Z();let o=He(a);return o?{ok:!0,eventId:o.id,published:o.published,...Sn(o,n,r,e.limit??50)}:Z()}let a=await z(t,e.id);return a?{ok:!0,eventId:a.id,published:a.published,...Sn(a,n,r,e.limit??50)}:Z()},!0),"mcp/events/create":Q(`createEvent`,async(e,t)=>ii(t,e)),"mcp/events/update":Q(`updateEvent`,async({id:e,patch:t},n)=>{if(!Object.keys(t).length)return{ok:!1,error:`EMPTY_PATCH`};let r=await z(n,e);if(!r)return Z();let i=ue(r),a=t.recurrence===void 0?r.recurrence:t.recurrence;return ii(n,{title:t.title??i.title,description:t.description??i.description,start:t.start??i.start,end:t.end??i.end,allDay:t.allDay??i.allDay,timezone:t.timezone??i.timezone,location:t.location??i.location,locationType:t.locationType??i.locationType,virtualUrl:t.virtualUrl??i.virtualUrl,status:t.status??i.status,organizer:t.organizer??i.organizer,organizerId:t.organizerId??i.organizerId,externalUrl:t.externalUrl??i.externalUrl,imageUrl:t.imageUrl??i.imageUrl,imageMediaId:t.imageMediaId??i.imageMediaId,categories:t.categories??b(i.categories),venueId:t.venueId??i.venueId,recurrence:a},r)}),"mcp/events/publish":Q(`getEvent`,async({id:e},t)=>{let n=await z(t,e);if(!n)return Z();let r={...n,published:!0,status:ce(!0,n.status),updatedAt:new Date().toISOString()};return await gt(t,r),{ok:!0,event:r}}),"mcp/events/unpublish":Q(`getEvent`,async({id:e},t)=>{let n=await z(t,e);if(!n)return Z();let r={...n,published:!1,status:ce(!1,n.status),updatedAt:new Date().toISOString()};return await gt(t,r),{ok:!0,event:r}}),"mcp/events/delete":Q(`getEvent`,async({id:e},t)=>({ok:!0,deleted:await yt(t,e)})),"mcp/events/exception/set":Q(`setOccurrenceException`,async(e,t)=>{let n=await z(t,e.eventId);if(!n)return Z();if(!n.recurrence)return{ok:!1,error:`NOT_RECURRING`};let i=e.recurrenceId.slice(0,10);if(!p(i)||(n.allDay?e.recurrenceId!==i:!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(e.recurrenceId)))return{ok:!1,error:`INVALID_RECURRENCE_ID`};if(!j(n,e.recurrenceId))return{ok:!1,error:`OCCURRENCE_NOT_FOUND`};let a;if(e.status===`cancelled`)a={recurrenceId:e.recurrenceId,status:`cancelled`};else{if(!e.overrides||!Object.keys(e.overrides).length)return{ok:!1,error:`OVERRIDES_REQUIRED`};let t=e.overrides,i=t.allDay??n.allDay,o=t.timezone??n.timezone,s=t.start,c=t.end;if(s===void 0!=(c===void 0))return{ok:!1,error:`START_AND_END_REQUIRED`};if(i!==n.allDay&&s===void 0)return{ok:!1,error:`REPLACEMENT_SCHEDULE_REQUIRED`};let l={...t};if(s&&c){let e=y({start:s,end:c,allDay:i,timezone:o});if(!e.dates)return $(e.errors.start??e.errors.end??e.errors.timezone??`Check the replacement schedule.`);l.start=e.dates.start,l.end=e.dates.end}if(t.virtualUrl!==void 0&&t.virtualUrl&&!E(t.virtualUrl))return $(`Virtual URL must use HTTP or HTTPS.`);if(t.virtualUrl!==void 0&&(l.virtualUrl=E(t.virtualUrl)),t.status!==void 0&&(l.status=ce(n.published,t.status)),t.externalUrl!==void 0&&t.externalUrl&&!E(t.externalUrl))return $(r);if(t.imageUrl!==void 0&&t.imageUrl&&!E(t.imageUrl))return $(`Image URL must use HTTP or HTTPS.`);if(!h(o))return $(`Choose a valid IANA timezone.`);t.categories&&(l.categories=b(t.categories)),a={recurrenceId:e.recurrenceId,status:`modified`,overrides:l}}let o=[...n.exceptions.filter(t=>t.recurrenceId!==e.recurrenceId),a].sort((e,t)=>e.recurrenceId.localeCompare(t.recurrenceId));if(o.length>500)return{ok:!1,error:`TOO_MANY_EXCEPTIONS`};let s={...n,exceptions:o,updatedAt:new Date().toISOString()};return await gt(t,s),{ok:!0,event:s}}),"mcp/events/exception/remove":Q(`removeOccurrenceException`,async({eventId:e,recurrenceId:t},n)=>{let r=await z(n,e);if(!r)return Z();let i=r.exceptions.filter(e=>e.recurrenceId!==t);if(i.length===r.exceptions.length)return{ok:!1,error:`EXCEPTION_NOT_FOUND`};let a={...r,exceptions:i,updatedAt:new Date().toISOString()};return await gt(n,a),{ok:!0,event:a}}),"mcp/venues/list":Q(`getSettings`,async(e,t)=>{let n=await B(t);return n?{ok:!0,venues:(await V(t,I(n,`venue`))).map(De).filter(Boolean)}:{ok:!0,venues:await Dt(t)}},!0),"mcp/venues/create":Q(`createVenue`,async(e,t)=>{let n=ai(e);return await Ct(t,n),{ok:!0,venue:n}}),"mcp/venues/update":Q(`updateVenue`,async({id:e,patch:t},n)=>{if(!Object.keys(t).length)return{ok:!1,error:`EMPTY_PATCH`};let r=await St(n,e);if(!r)return Z();let i=ai({...r,...t},r);return await Ct(n,i),{ok:!0,venue:i}}),"mcp/venues/delete":Q(`getEvent`,async({id:e},t)=>await St(t,e)?await Tt(t,e)?{ok:!1,error:`VENUE_IN_USE`}:{ok:!0,deleted:await wt(t,e)}:Z()),"mcp/settings/get":Q(`getSettings`,async(e,t)=>({ok:!0,defaultTimezone:await t.settings.get(`defaultTimezone`)??`UTC`,collections:await Ze(t)??null,legacyReads:await Qe(t)}),!0),"mcp/settings/update":Q(`updateSettings`,async({defaultTimezone:e,collections:t,legacyReads:n},r)=>{if(!h(e))return{ok:!1,error:`INVALID_TIMEZONE`};if(t)try{await nt(r,t)}catch(e){return{ok:!1,error:`INVALID_COLLECTIONS`,details:e instanceof Error?e.message:`Review the collection schemas.`}}return n!==void 0&&await $e(r,n),await r.settings.set(`defaultTimezone`,e),{ok:!0,defaultTimezone:e,legacyReads:await Qe(r)}},!0)},si=(e,t)=>`state:eventual-migration:`+e+`:`+encodeURIComponent(t);function ci(e,t){let n=new Set(e.fields.map(e=>e.slug)),r=Object.fromEntries(Object.entries(t).filter(([e,t])=>n.has(e)&&t!=null));for(let t of e.fields)t.required&&!(t.slug in r)&&t.default===void 0&&i(`Missing required target field `+t.slug);return r}async function li(e,t={}){let n=t.locale??`fr`,r=t.dryRun===!0,o={ok:!1,dryRun:r,locale:n,venueCollection:t.venueCollection??`venues`,venues:[],events:[],summary:{totalVenues:0,migratedVenues:0,totalEvents:0,migratedEvents:0,errors:0}},s=null,c=`state:eventual-migration-lock`;try{Intl.getCanonicalLocales(n)[0]!==n&&i(`Use a canonical BCP 47 locale.`),r&&(o.warnings=[`Execution assigns native IDs and checks site locales and other plugins' content policies.`]),(!e.schema||!e.content?.create||!e.content.publish||!e.content.getVersioned)&&i(`Native schema, write and publish APIs are required.`);let l=await F(e),u=await L(e);u||i(`Apply the event blueprint before migrating.`);let d=I(u,`venue`),f=it(u,`venue`);u.fields.some(e=>e.slug===f)||i(`Upgrade the bound venue reference schema before migration.`),o.venueCollection=t.venueCollection??(typeof d==`string`?d:l.some(e=>e.slug===`locations`)?`locations`:`venues`),d!==o.venueCollection&&i(`venueCollection must match the events.venue reference target.`);let p=l.find(e=>e.slug===o.venueCollection);p||i(`Target venue collection is missing.`);for(let e of[u,p]){let t=e.fields.find(e=>e.slug===`legacy_id`);(!t?.unique||!t.indexed)&&i(e.slug+` requires unique indexed legacy_id field.`),e.fields.some(e=>e.slug===`legacy_metadata`&&e.type===`json`)||i(e.slug+` requires legacy_metadata JSON.`)}for(let e of[`start_date`,`end_date`,`all_day`,`timezone`,`description`,`event_status`,`calendar_uid`,`exceptions`,`occurrence_content`,`legacy_metadata`,`image_url`,`organizer_details`,`categories`,`location`])u.fields.some(t=>t.slug===e)||i(`Update the events blueprint: missing `+e);if(!r){let t=await e.kv.getVersioned(c);t&&t.value.until>Date.now()&&i(`Migration is already running.`),(await e.kv.compareAndSet(c,t?.revision??null,{until:Date.now()+3e5})).applied||i(`Migration lock conflict; retry.`),s=await e.kv.getVersioned(c)}let m=await V(e,o.venueCollection),h=await V(e,u.slug),g=new Map([[o.venueCollection,new Map(m.filter(e=>typeof e.data.legacy_id==`string`).map(e=>[e.data.legacy_id,e]))],[u.slug,new Map(h.filter(e=>typeof e.data.legacy_id==`string`).map(e=>[e.data.legacy_id,e]))]]),_=new Map;for(let[n,a]of Object.entries(t.venueMapping??{}))(typeof a!=`string`||!a)&&i(`venueMapping values must be non-empty native IDs.`),await e.content.get(o.venueCollection,a)||i(`Mapped venue does not exist: `+a),_.set(n,a),r||await e.kv.set(si(o.venueCollection,n),{id:a,published:!0,status:`complete`});for(let t of m)if(typeof t.data.legacy_id==`string`&&!_.has(t.data.legacy_id)){let n=await e.kv.get(si(o.venueCollection,t.data.legacy_id));(!n||n.status===`complete`||t.status===`published`)&&_.set(t.data.legacy_id,t.id)}let v=(e,t)=>ci(p,{name:a(e.name).trim(),title:a(e.name).trim(),street:a(e.street),street2:a(e.street2),address:a(e.street),streetAddress:a(e.street),locality:a(e.locality),city:a(e.locality),region:a(e.region),state:a(e.region),postal_code:a(e.postalCode),postalCode:a(e.postalCode),zip:a(e.postalCode),country:a(e.country),legacy_id:t,legacy_metadata:JSON.stringify(e)}),y=`venues`,b;if(t.cursor){let e=JSON.parse(t.cursor);(![`venues`,`events`].includes(e.phase)||e.locale!==n||e.collection!==o.venueCollection||e.cursor!==void 0&&typeof e.cursor!=`string`)&&i(`Invalid migration cursor.`),y=e.phase,b=e.cursor}let x=t.limit??25;(!Number.isInteger(x)||x<1||x>100)&&i(`limit must be between 1 and 100.`);let S=r?fr(e):await pr(e),C=await e.kv.get(`state:eventual-calendar-host`),w=async()=>{r||!s||((await e.kv.compareAndSet(c,s.revision,{until:Date.now()+3e5})).applied||i(`Migration lease expired or changed; retry the batch.`),s=await e.kv.getVersioned(c))},T=async(t,a,o,s,c)=>{await w();let l=si(t,o),d=await e.kv.get(l),f=g.get(t)?.get(o);if(d?.id){let n=await e.content.get(t,d.id);n||i(`Native item removed; restore it explicitly.`),f=n}if(f){t===u.slug&&f.locale&&f.locale!==n&&i(`Migration identity belongs to locale `+f.locale+`; use its original locale.`);let a=typeof f.data.legacy_metadata==`string`?JSON.parse(f.data.legacy_metadata):f.data.legacy_metadata,o=d&&d.status!==`complete`&&d.token&&a?.migrationToken===d.token,s=o&&c&&f.status!==`published`?`resume_publication`:`none`;if(!r&&o&&c&&f.status!==`published`){let n=await e.content.getVersioned(t,f.id);n||i(`Created item disappeared.`),await e.content.publish(t,f.id,{_rev:n._rev})}return!r&&(!d||o)&&await e.kv.set(l,{id:f.id,published:c,status:`complete`,token:d?.token}),{id:f.id,existed:!0,action:s}}if(r)return{id:``,existed:!1,action:`create`};let p=crypto.randomUUID(),m=typeof s.legacy_metadata==`string`?JSON.parse(s.legacy_metadata):s.legacy_metadata??{};await e.kv.set(l,{id:``,published:c,status:`creating`,token:p});let h=await e.content.create(t,ci(a,{...s,legacy_metadata:JSON.stringify({...m,migrationToken:p})}),{locale:n});if(g.get(t).set(o,h),await w(),await e.kv.set(l,{id:h.id,published:c,status:`created`,token:p}),c&&h.status!==`published`){let n=await e.content.getVersioned(t,h.id);n||i(`Created item disappeared.`),await e.content.publish(t,h.id,{_rev:n._rev})}return await w(),await e.kv.set(l,{id:h.id,published:c,status:`complete`,token:p}),{id:h.id,existed:!1,action:`create`}};for(;x>0;){let t=await e.storage[y].query({limit:x,cursor:b});t.hasMore&&(!t.cursor||t.cursor===b)&&i(`Incomplete legacy storage cursor.`);for(let n of t.items){x--;let t=n.id,s=n.data,c=a(y===`venues`?s.name:s.title).trim(),l=y===`venues`?o.venues:o.events;try{if(y===`venues`&&_.has(t)){l.push({legacyId:t,nativeId:_.get(t),titleOrName:c||t,status:`already_exists`});continue}c||i(`Missing title or venue name.`);let n,d=!1,m,h;if(y===`venues`)m=p,h=o.venueCollection,n=v(s,t),d=!0;else{h=u.slug,m=u;let l=s;Object.keys(l.translations??{}).length&&i(`Manual translations need explicit native locale rows. Migration skipped; source retained.`);let p=l.venueId?_.get(l.venueId)??(await e.kv.get(si(o.venueCollection,l.venueId)))?.id:void 0;if(r&&l.venueId&&!p){let t=await e.storage.venues.get(l.venueId);a(t?.name).trim()&&v(t,l.venueId)&&(p=`planned:`+l.venueId)}l.venueId&&!p&&i(`Unmapped venue `+l.venueId);let g=p&&!p.startsWith(`planned:`)?await e.content.get(o.venueCollection,p):void 0;p&&!p.startsWith(`planned:`)&&!g&&i(`Mapped venue was removed.`),l.published&&p&&!p.startsWith(`planned:`)&&g?.status!==`published`&&i(`Publish the mapped venue before migrating a published event.`),l.imageMediaId&&!await e.media?.get(l.imageMediaId)&&i(`Legacy media item is unavailable.`);let y=new Set([`title`,`description`,`location`,`organizer`]),b=(l.exceptions??[]).map(e=>({...e,overrides:e.overrides?Object.fromEntries(Object.entries(e.overrides).filter(([e])=>!y.has(e)&&e!==`locale`)):void 0})),x=(l.exceptions??[]).flatMap(e=>{let t=Object.fromEntries(Object.entries(e.overrides??{}).filter(([e])=>y.has(e)));return Object.keys(t).length?[{recurrenceId:e.recurrenceId,overrides:t}]:[]}),w=b.filter(e=>e.status===`cancelled`||Object.keys(e.overrides??{}).length),T=l.organizerId?await e.storage.organizers?.get(l.organizerId):void 0,E=Fe({start:l.start,end:l.end,all_day:l.allDay,timezone:l.timezone,recurrence:l.recurrence,exceptions:w,occurrence_content:x});n=ci(m,{title:c,description:Te(a(l.description)),excerpt:N(l.description).slice(0,160),...E,location_type:l.locationType??`physical`,location:a(l.location),[f]:p,virtual_url:l.virtualUrl||void 0,external_url:l.externalUrl||void 0,organizer:a(l.organizer),organizer_details:T?JSON.stringify(T):void 0,categories:JSON.stringify(l.categories??[]),featured_image:l.imageMediaId?{id:l.imageMediaId,...l.imageUrl?{src:l.imageUrl}:{}}:void 0,image_url:l.imageMediaId?void 0:l.imageUrl||void 0,event_status:[`cancelled`,`postponed`,`rescheduled`].includes(l.status??``)?l.status:`published`,recurrence:l.recurrence?JSON.stringify(l.recurrence):void 0,exceptions:JSON.stringify(w),occurrence_content:JSON.stringify(x),previous_start_date:l.previousStartDate,schedule_history:l.scheduleHistory?JSON.stringify(l.scheduleHistory):void 0,legacy_id:t,calendar_uid:G(t,C??S),legacy_metadata:JSON.stringify({createdAt:l.createdAt,updatedAt:l.updatedAt,organizerId:l.organizerId,locale:l.locale,description:l.description,exceptions:l.exceptions})}),He({id:t,status:`published`,type:`events`,data:n})||i(`Invalid migrated event payload.`),d=l.published===!0}let g=await T(h,m,t,n,d);y===`venues`&&_.set(t,g.id||`planned:`+t),l.push({legacyId:t,nativeId:g.id,action:g.action,titleOrName:c,status:g.existed?`already_exists`:r?`planned`:`migrated`,...r?{payload:n}:{}})}catch(e){l.push({legacyId:t,nativeId:``,titleOrName:c,status:`error`,error:e instanceof Error?e.message:String(e)})}}if(t.hasMore){o.nextCursor=JSON.stringify({phase:y,cursor:t.cursor,locale:n,collection:o.venueCollection});break}if(y===`events`)break;y=`events`,b=void 0,x||(o.nextCursor=JSON.stringify({phase:y,locale:n,collection:o.venueCollection}))}r||await hr(e),o.ok=!o.venues.concat(o.events).some(e=>e.status===`error`)}catch(e){o.error=e instanceof Error?e.message:String(e)}finally{s&&await e.kv.compareAndDelete(c,s.revision)}return o.summary={totalVenues:o.venues.length,migratedVenues:o.venues.filter(e=>e.status===`migrated`).length,totalEvents:o.events.length,migratedEvents:o.events.filter(e=>e.status===`migrated`).length,errors:o.venues.concat(o.events).filter(e=>e.status===`error`).length+(o.error?1:0)},o}async function ui(e,t,n){let r=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(JSON.stringify([e,t,n])));return`import-${Array.from(new Uint8Array(r),e=>e.toString(16).padStart(2,`0`)).join(``)}`}function di(e){return!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/.test(e)||!Number.isFinite(Date.parse(e))?!1:new Date(e).toISOString().replace(`.000Z`,`Z`)===e.replace(`.000Z`,`Z`)}function fi(e){return h(e.timezone)?e.allDay?p(e.start)&&p(e.end)&&e.end>=e.start:di(e.start)&&di(e.end)&&Date.parse(e.end)>=Date.parse(e.start):!1}async function pi(e,t,n,r,a,o){[n.createdAt,n.updatedAt].every(di)||i(`Invalid record timestamp.`);let s=new Date().toISOString();if(t.collection!==`events`){let e=n;return e.name.trim()||i(`Name is required.`),t.collection===`organizers`&&[n.website,n.contactUrl].some(e=>e&&!E(e))&&i(`Public URLs must use HTTP(S).`),{...n,name:e.name.trim(),id:r,updatedAt:s}}let c=n;(!fi(c)||c.recurrence&&!O(c.recurrence))&&i(`Invalid schedule or recurrence.`);let l=le(ue({...c,published:!1,status:`draft`}),{start:c.start,end:c.end});l.data||i(l.error);let u={...c,...l.data,id:r,createdAt:c.createdAt,updatedAt:s};if(t.mode!==`restore`)for(let e of[`calendarUid`,`translationGroup`,`calendarSequence`,`scheduleHistory`,`previousStartDate`,`publicUrl`])delete u[e];for(let n of[`venueId`,`organizerId`]){let r=c[n];if(!r)continue;let s=n===`venueId`?`venues`:`organizers`,l=t.mode===`restore`?r:await ui(t.source,s,r);if(!e.has(s+`:`+l)){let e=`Missing ${s} reference: ${r}. Import referenced records first.`;a&&i(e),o.push(e)}u[n]=l}c.imageMediaId&&i(`Media is not restored by this tool.`);for(let e of u.exceptions){let t=j(u,e.recurrenceId);if(t||i(`Invalid exception recurrenceId.`),e.status===`modified`){let n=e.overrides;(!n||!Object.keys(n).length)&&i(`Modified exceptions require overrides.`),n.imageMediaId&&i(`Exception media IDs require a host media restore.`),[`virtualUrl`,`externalUrl`,`imageUrl`].some(e=>{let t=n[e];return t&&!E(t)})&&i(`Exception URLs must use HTTP(S).`),(n.start===void 0!=(n.end===void 0)||n.allDay!==void 0&&n.allDay!==t.allDay&&n.start===void 0)&&i(`Replacement schedule requires start and end.`),fi({...t,...n})||i(`Invalid exception schedule.`),n.status=`draft`}}return(new Set(u.exceptions.map(e=>e.recurrenceId)).size!==u.exceptions.length||!Ce(u))&&i(`Duplicate or invalid exception IDs.`),c.scheduleHistory?.some(e=>!fi(e)||!di(e.changedAt))&&i(`Invalid schedule history.`),c.previousStartDate&&!p(c.previousStartDate)&&!di(c.previousStartDate)&&i(`Invalid previous start.`),c.scheduleHistory&&(u.scheduleHistory=c.scheduleHistory),c.previousStartDate&&(u.previousStartDate=c.previousStartDate),u}async function mi(e,t,n){if(e=R(e),await B(e))return{ok:!1,preview:!n,error:`NATIVE_COLLECTIONS_ACTIVE`,details:`Legacy imports are disabled when native collections are active.`,rows:[]};if(!Qr(n?`importRecords`:`previewImport`,t)||new TextEncoder().encode(JSON.stringify(t)).length>65536)return{ok:!1,error:`VALIDATION_ERROR`,maxBytes:65536};let r=[],a=new Set,o=await Promise.all(t.records.map(e=>t.mode===`restore`?e.sourceId:ui(t.source,t.collection,e.sourceId))),s=e.storage[t.collection],c=await s.getMany([...new Set(o)]),l=new Set;if(t.collection===`events`)for(let[n,r]of[[`venueId`,`venues`],[`organizerId`,`organizers`]]){let i=[...new Set(t.records.flatMap(e=>$r(`events`,e.data)&&e.data[n]?[e.data[n]]:[]))],a=await Promise.all(i.map(e=>t.mode===`restore`?e:ui(t.source,r,e)));if(a.length)for(let t of(await e.storage[r].getMany(a)).keys())l.add(r+`:`+t)}for(let[u,d]of t.records.entries()){let f=o[u];try{$r(t.collection,d.data)||i(`Record does not match its collection schema.`),d.sourceId!==d.data.id&&i(`sourceId must match the record ID.`),a.has(f)&&i(`Duplicate source ID in this batch.`),a.add(f);let o=[],p=await pi(l,t,structuredClone(d.data),f,n,o),m=c.has(f)?`skipped`:n?lt(e)===0?`pending`:(await s.compareAndSet(f,null,p)).applied?`imported`:`skipped`:`ready`;r.push({row:u+1,sourceId:d.sourceId,id:f,status:m,...o.length?{warnings:o}:{}})}catch(e){r.push({row:u+1,sourceId:d.sourceId,id:f,status:`error`,error:e instanceof Error?e.message:`Import failed.`})}}return{ok:r.every(e=>e.status!==`error`&&e.status!==`pending`),preview:!n,...r.some(e=>e.status===`pending`)?{error:`SANDBOX_BUDGET_EXCEEDED`,details:`Retry pending rows; existing IDs are skipped.`}:{},rows:r}}const hi={"mcp/transfer/preview":{permission:`plugins:manage`,handler:(e,t)=>mi(t,e.input,!1)},"mcp/transfer/import":{permission:`plugins:manage`,handler:(e,t)=>mi(t,e.input,!0)},"mcp/transfer/export":{permission:`plugins:manage`,handler:async(e,t)=>{if(!Qr(`exportRecords`,e.input))return{ok:!1,error:`VALIDATION_ERROR`};let n=e.input,r=await B(t);if(r){let e=n.collection===`venues`?I(r,`venue`):n.collection===`organizers`?I(r,`organizer_ref`):r.slug,i=await t.content.list(e,{limit:n.limit??5,cursor:n.cursor});if(i.hasMore&&(!i.cursor||i.cursor===n.cursor))return{ok:!1,error:`INCOMPLETE_PAGE`};let a=i.items.map(e=>({sourceId:e.id,data:e.data,metadata:{slug:e.slug,locale:e.locale,status:e.status,translationGroup:e.translationGroup,createdAt:e.createdAt,updatedAt:e.updatedAt,publishedAt:e.publishedAt,scheduledAt:e.scheduledAt,draftRevisionId:e.draftRevisionId,liveRevisionId:e.liveRevisionId}}));return new TextEncoder().encode(JSON.stringify(a)).length>65536?{ok:!1,error:`EXPORT_PAGE_TOO_LARGE`,details:`Retry with limit 1.`}:{ok:!0,format:`native-content-v1`,collection:e,records:a,...i.hasMore?{nextCursor:i.cursor}:{}}}let i=await t.storage[n.collection].query({limit:n.limit??5,cursor:n.cursor});if(i.hasMore&&!i.cursor)return{ok:!1,error:`INCOMPLETE_PAGE`};let a=i.items.map(e=>({sourceId:e.id,data:e.data}));return new TextEncoder().encode(JSON.stringify(a)).length>65536?{ok:!1,error:`EXPORT_PAGE_TOO_LARGE`,details:`Retry with limit 1.`}:{ok:!0,collection:n.collection,records:a,...i.hasMore?{nextCursor:i.cursor}:{}}}},"mcp/transfer/migrateToNative":{permission:`plugins:manage`,handler:async(e,t)=>{let n=e.input??{};return Qr(`migrateToNative`,n)?li(t,n):{ok:!1,error:`VALIDATION_ERROR`}}}};async function gi(e,t){if(t=R(t),e.collection===await Xe(t)){if(!Pe.some(t=>Object.hasOwn(e.content,t))||e.isNew&&![`start`,`end`,`start_date`,`end_date`].some(t=>e.content[t]!=null&&e.content[t]!==``))return e.content;try{let n={},r;if(e.id&&(r=await t.content?.get(e.collection,e.id),r&&(n=r.data),r?.draftRevisionId&&t.content?.getRevision)){let i=await t.content.getRevision(e.collection,e.id,r.draftRevisionId);i&&(n=i.data)}for(let t of[`calendar_uid`,`legacy_id`])e.id&&Object.hasOwn(e.content,t)&&e.content[t]!==n[t]&&i(t+` cannot be changed after creation.`);if(r?.status===`draft`&&![`start`,`end`,`start_date`,`end_date`].some(t=>({...n,...e.content})[t]))return e.content;let a=Fe({...n,...e.content},{allowStaleOccurrenceCopy:!Object.hasOwn(e.content,`occurrence_content`)||JSON.stringify(P(e.content.occurrence_content)??[])===JSON.stringify(P(n.occurrence_content)??[])}),o={...e.content};for(let e of[`start`,`end`,`start_date`,`end_date`,`all_day`,`timezone`])e in a&&(o[e]=a[e]);if(e.id&&Object.hasOwn(e.content,`all_day`))for(let e of a.all_day?[`start`,`end`]:[`start_date`,`end_date`])o[e]=null;if(r?.status===`published`){let n=e=>({start:String(e[e.all_day?`start_date`:`start`]||``),end:String(e[e.all_day?`end_date`:`end`]||``),allDay:!!e.all_day,timezone:String(e.timezone||`UTC`)}),i=n(r.data),s=n(a),c=e=>e&&Object.entries(i).every(([t,n])=>e[t]===n);if(i.start&&i.end&&!c(s)){let n=(await F(t)).find(t=>t.slug===e.collection),a=e=>n?.fields.some(t=>t.slug===e),s=P(r.data.schedule_history??o.schedule_history),l=Array.isArray(s)?s:[];a(`schedule_history`)&&!c(l[0])&&(o.schedule_history=JSON.stringify([{...i,changedAt:new Date().toISOString()},...l].slice(0,10))),a(`previous_start_date`)&&(o.previous_start_date=i.start),r.data.event_status!==`cancelled`&&(!Object.hasOwn(e.content,`event_status`)||e.content.event_status===r.data.event_status)&&(o.event_status=`rescheduled`)}}return o}catch(e){return{__emdashSandboxHookResult:!0,version:1,error:{code:`SAVE_REJECTED`,reason:e instanceof Error?e.message:String(e)}}}}}async function _i(e,t){if(t&&=R(t),e.collection===(t?await Xe(t):`events`))try{let n=e.content.data&&typeof e.content.data==`object`?e.content.data:e.content;if(Fe(n,{allowStaleOccurrenceCopy:!0}),t&&(n.venue_id??n.venue)){let e=I(await L(t),`venue`),r=rt(n.venue_id??n.venue);(typeof e!=`string`||typeof r!=`string`||(await t.content?.get(e,r))?.status!==`published`)&&i(`Publish a valid referenced venue before publishing or scheduling this event.`)}if(t&&(n.organizer_id??n.organizer_ref??n.organizerId)){let e=rt(n.organizer_id??n.organizer_ref??n.organizerId);if(e){let n=I(await L(t),`organizer_ref`),r=await t.content?.get(n,e);(!r||r.status!==`published`)&&i(`Publish the referenced organizer before publishing or scheduling this event.`)}else i(`Choose a valid saved organizer.`)}}catch(e){return{cancel:!0,reason:e instanceof Error?e.message:String(e)}}}async function vi(e,t,n){let r=await Ze(n);if(r&&![r.venues,r.organizers].includes(e))return;let a=await L(n);if(!a)return;let o=I(a,`venue`),s=I(a,`organizer_ref`);if(e!==o&&e!==s)return;(typeof t!=`string`||!t)&&i(`Cannot verify this dependency. Reload the entry.`);let c=await n.content?.get(e,t),l=new Set([t]);if(c&&n.content?.getTranslations){let r=await n.content.getTranslations(e,t);for(let e of r.translations)l.add(e.id)}for(let t of await V(n,a.slug)){if(t.status!==`published`&&t.status!==`scheduled`)continue;let r=[t.data];if((t.status===`scheduled`||t.scheduledAt)&&t.draftRevisionId&&n.content?.getRevision){let e=await n.content.getRevision(a.slug,t.id,t.draftRevisionId);e||i(`Scheduled event revision could not be verified. Retry before changing this dependency.`),r.push(e.data)}if((t.status===`scheduled`||t.scheduledAt)&&t.draftRevisionId&&!n.content?.getRevision&&i(`Scheduled event revision access is required to verify this dependency.`),r.some(t=>e===o&&l.has(rt(t.venue_id??t.venue)??``)||e===s&&l.has(rt(t.organizer_id??t.organizer_ref)??``)))return`This `+(e===o?`venue`:`organizer`)+` is used by published or scheduled event "`+String(t.data.title??t.id)+`". Reassign or unpublish the event first.`}}async function yi(e,t){if(t){t=R(t);try{let n=e.content.data&&typeof e.content.data==`object`?e.content.data:{},r=await vi(e.collection,e.content.id??n.id,t);if(r)return{cancel:!0,reason:r}}catch(e){return{cancel:!0,reason:e instanceof Error?e.message:`Dependencies could not be verified. Retry before unpublishing.`}}}}async function bi(e,t){if(t=R(t),e.collection===await Xe(t)){await hr(t);return}let n=await vi(e.collection,e.id,t);n&&i(n)}const xi=t=>e({status:503,headers:{"content-type":`text/plain; charset=utf-8`,"cache-control":`no-store`,"retry-after":`60`},body:{kind:`text`,value:t.message}});async function Si(e,t,n){let r=R(e),i=await n(r),a=await vn(r,t);return a?$t(i,a):i}const Ci={hooks:{"plugin:activate":async(e,t)=>{await yn(t)},"content:beforeSave":gi,"content:beforeDelete":bi,"content:beforePublish":_i,"content:beforeSchedule":_i,"content:beforeUnpublish":yi},routes:{...oi,...hi,admin:{permission:`content:edit_any`,handler:async(e,t)=>Si(t,e.ui?.locale,t=>Xt(e.input,{...t,site:{...t.site,url:t.site.url||new URL(e.request.url).origin}},e.user))},"admin/editor/schedule":{permission:`content:edit_any`,handler:async(e,t)=>Si(t,e.ui?.locale,t=>Xn(e,t))},publicEvents:t({public:!0,methods:[`GET`],request:{body:`none`},cacheControl:`public, max-age=60`,handler:async(e,t)=>{let n=await Ut(e.input,t);if(n.error===`SANDBOX_BUDGET_EXCEEDED`)throw new at;return n}}),publicEventImage:t({public:!0,methods:[`GET`],request:{body:`none`},response:`raw`,cacheControl:`no-store`,handler:async(e,t)=>{try{return await $n(e.input,t)}catch(e){if(e instanceof at)return xi(e);throw e}}}),calendar:t({public:!0,methods:[`GET`],request:{body:`none`},response:`raw`,cacheControl:`public, max-age=300`,handler:async(t,n)=>{try{let r=new URL(t.request.url,`http://localhost`),i=r.searchParams.get(`locale`)||void 0;try{i&&Intl.getCanonicalLocales(i)}catch{return e({status:400,headers:{"content-type":`text/plain; charset=utf-8`,"cache-control":`no-store`},body:{kind:`text`,value:`Invalid locale.`}})}let a=r.searchParams.get(`strict`)===`true`,o=r.searchParams.get(`category`)||void 0,s=r.host||`localhost`;return e({status:200,headers:{"content-type":`text/calendar; charset=utf-8`},body:{kind:`text`,value:await gr(n,s,{locale:i,strict:a,category:o})}})}catch(e){return xi(e instanceof ft||e instanceof at?e:Error(`Calendar feed unavailable; retry later.`))}}})}};export{Ci as default};
package/docs/history.md CHANGED
@@ -1,16 +1,16 @@
1
- # History and release evidence
2
-
3
- Current instructions are [using Eventual](user-guide.md), [setup](collection-setup.md), [upgrading](upgrade-0.13.0.md) and the [developer guide](native-modernization.md). [CHANGELOG](../CHANGELOG.md) summarizes earlier versions.
4
-
5
- The [0.14.1 acceptance record](../audit/releases/0.14.1/README.md) covers the EmDash 1.2.0/1.4.0 compatibility release, the local test-site native gate, and the packed-consumer editor acceptance. It is not a publication record.
6
-
7
- The [0.14.0 acceptance record](../audit/releases/0.14.0/README.md) retains publication-time CIDs, checksums, verification and BBHC deployment evidence. Its figures and signed records describe that release, not a fresh build of today's documentation. Listing-documentation updates can change the profile CID while the versioned release remains unchanged.
8
-
9
- Older release notes, prototype instructions, implementation plans and handovers remain available in the [documentation snapshot before consolidation](https://github.com/Vermeulen-Solutions/eventual-emdash-sandbox/tree/9bd38934de72c562639093e38a56fe6b3e3e2818/docs). They are historical evidence, not installation instructions:
10
-
11
- - [0.13.0 native-content release](https://github.com/Vermeulen-Solutions/eventual-emdash-sandbox/blob/9bd38934de72c562639093e38a56fe6b3e3e2818/docs/release-notes-0.13.0.md).
12
- - [EmDash 1.0.1 editor-adapter runbook](https://github.com/Vermeulen-Solutions/eventual-emdash-sandbox/blob/9bd38934de72c562639093e38a56fe6b3e3e2818/docs/editor-upgrade.md); the current plugin uses EmDash 1.2+ without that adapter.
13
- - [0.14.0 pre-release audit](https://github.com/Vermeulen-Solutions/eventual-emdash-sandbox/blob/9bd38934de72c562639093e38a56fe6b3e3e2818/docs/0.14.0-audit-handover.md); acceptance later repaired weekday translations and published the release.
14
- - [RPC implementation proposal](https://github.com/Vermeulen-Solutions/eventual-emdash-sandbox/blob/9bd38934de72c562639093e38a56fe6b3e3e2818/docs/sandbox-rpc-implementation-plan.md); proposed background jobs and capacity targets are not implemented guarantees.
15
-
16
- The unsupported prototype/private-form and two-package installation proposals are retired. Current limitations and open API work are summarized in the developer guide, rather than repeated across handovers.
1
+ # History and release evidence
2
+
3
+ Current instructions are [using Eventual](user-guide.md), [setup](collection-setup.md), [upgrading](upgrade-0.13.0.md) and the [developer guide](native-modernization.md). [CHANGELOG](../CHANGELOG.md) summarizes earlier versions.
4
+
5
+ The [0.14.1 acceptance record](../audit/releases/0.14.1/README.md) covers the EmDash 1.2.0/1.4.0 compatibility release, the local test-site native gate, and the packed-consumer editor acceptance. It is not a publication record.
6
+
7
+ The [0.14.0 acceptance record](../audit/releases/0.14.0/README.md) retains publication-time CIDs, checksums, verification and BBHC deployment evidence. Its figures and signed records describe that release, not a fresh build of today's documentation. Listing-documentation updates can change the profile CID while the versioned release remains unchanged.
8
+
9
+ Older release notes, prototype instructions, implementation plans and handovers remain available in the [documentation snapshot before consolidation](https://github.com/Vermeulen-Solutions/eventual-rsvp-core/tree/9bd38934de72c562639093e38a56fe6b3e3e2818/docs). They are historical evidence, not installation instructions:
10
+
11
+ - [0.13.0 native-content release](https://github.com/Vermeulen-Solutions/eventual-rsvp-core/blob/9bd38934de72c562639093e38a56fe6b3e3e2818/docs/release-notes-0.13.0.md).
12
+ - [EmDash 1.0.1 editor-adapter runbook](https://github.com/Vermeulen-Solutions/eventual-rsvp-core/blob/9bd38934de72c562639093e38a56fe6b3e3e2818/docs/editor-upgrade.md); the current plugin uses EmDash 1.2+ without that adapter.
13
+ - [0.14.0 pre-release audit](https://github.com/Vermeulen-Solutions/eventual-rsvp-core/blob/9bd38934de72c562639093e38a56fe6b3e3e2818/docs/0.14.0-audit-handover.md); acceptance later repaired weekday translations and published the release.
14
+ - [RPC implementation proposal](https://github.com/Vermeulen-Solutions/eventual-rsvp-core/blob/9bd38934de72c562639093e38a56fe6b3e3e2818/docs/sandbox-rpc-implementation-plan.md); proposed background jobs and capacity targets are not implemented guarantees.
15
+
16
+ The unsupported prototype/private-form and two-package installation proposals are retired. Current limitations and open API work are summarized in the developer guide, rather than repeated across handovers.
@@ -1,99 +1,99 @@
1
- # Developer guide — Eventual 0.15.0
2
-
3
- EmDash collections own content, rich text, languages, drafts, revisions and publication. Eventual's sandbox supplies schedule validation, recurrence, saved-entry controls and feeds. See [setup](collection-setup.md) and [upgrading](upgrade-0.13.0.md).
4
-
5
- The [public feed caching guide](public-feed-caching.md) describes additive
6
- dependency/expiry metadata, direct runtime dispatch and the host's explicit opt-in.
7
-
8
- ## Installation and plugin ID
9
-
10
- Registry installations use the host's sandbox runner and downloaded bundle. Config-managed installations register the source descriptor in `sandboxed: [eventual]`. Use one backend per site. Cloudflare Registry hosts need Worker Loader and PluginBridge: [EmDash sandbox setup](https://docs.emdashcms.com/deployment/plugin-sandbox/).
11
-
12
- **Use the installed plugin ID in URLs and MCP names.** Config-managed installs normally use `eventual`; Registry installs have generated IDs such as `r_hxn32uyal53iahxf`. Read it from the install result or authenticated `GET /_emdash/api/admin/plugins`. MCP names are `<pluginId>__<toolName>`.
13
-
14
- Astro/schema/transfer helpers come from the npm package
15
- [`@vermeulen.solutions/eventual`](https://www.npmjs.com/package/@vermeulen.solutions/eventual)
16
- (0.18.1 and later), not the Registry `.tar.gz`. Install the version that matches the Registry backend:
17
-
18
- ```sh
19
- npm install @vermeulen.solutions/eventual@0.18.1
20
- ```
21
-
22
- Import it as `@vermeulen.solutions/eventual/astro`, `@vermeulen.solutions/eventual/schema` and so on; the plugin ID stays `eventual`.
23
- Releases before 0.18.1 were not on npm; their source archives (`eventual-<version>.tgz`) are attached to the GitHub releases.
24
-
25
- To build the same helpers from the release checkout, run `npm ci`, `npm run build`
26
- and `npm pack`. Keep helper and backend versions aligned.
27
-
28
- Source tooling needs Node 24+. Peer ranges are in [package.json](../package.json); release acceptance uses EmDash/Admin/Block Kit **1.2.0 and 1.4.0**, Astro 7.3.x/7.4.x and React 19. The source `@vermeulen.solutions/eventual/install` lane accepts 1.2.0 and 1.4.0; Registry installs never execute that transform.
29
-
30
- | Host | Status | Notes |
31
- | --- | --- | --- |
32
- | 1.2.0 | supported, unit-tested | Panel Enter/validation is scoped to the outer content-editor form; Cloudflare cross-isolate plugin mutations can fail. |
33
- | 1.3.x | supported, untested | Same form/Cloudflare limitations; includes the plugin-storage cursor fix. |
34
- | 1.4.x | supported, full acceptance | Recommended. Fixes nested Block Kit forms and Cloudflare plugin mutations. |
35
-
36
- ## Public routes
37
-
38
- Routes are relative to `/_emdash/api/plugins/<pluginId>/`.
39
-
40
- | Route | Inputs and behavior |
41
- | --- | --- |
42
- | `GET publicEvents` | Inclusive `from`/`through` dates (YYYY-MM-DD); default UTC today through 180 days later; maximum 366 inclusive dates. Also `locale`, `strict` (false), `category`, `publicUrls` (true). |
43
- | `GET calendar` | Raw text/calendar; fixed window from UTC today through 365 days later. Supports locale, strict and category. |
44
- | `GET publicEventImage?eventId=…` | Published featured image with MIME/size checks; absent, unpublished or disabled legacy images return 404. |
45
-
46
- `strict=true` omits events without the requested translation; false can use another language with a `[FR]`/`[EN]` title prefix. Categories match without case sensitivity. `publicUrls=false` skips native canonical-URL lookups; slug/id remain available for site-owned links.
47
-
48
- JSON success:
49
-
50
- ```json
51
- {"success":true,"data":{"ok":true,"from":"2026-11-01","through":"2026-11-30","events":[]}}
52
- ```
53
-
54
- The feed has no top-level locale. Event rows carry title, description/plain text, optional descriptionBlocks, start/end, allDay, timezone, location, organizer, externalUrl, imageUrl, categories, venue and directionsUrl. Optional native metadata includes locale, translationGroup, slug and publicUrl. Business status is `status`, not `eventStatus`: see [PublicEvent](../src/public-event.ts). All-day end dates are inclusive here and exclusive in ICS.
55
-
56
- Handle both `success:false` host failures and `data.ok:false` plugin failures. EmDash 1.2.0 JSON configuration/RPC failures use HTTP 400, ROUTE_ERROR and private/no-store caching. Preserve errors instead of substituting stale rows or a successful empty feed.
57
-
58
- ## Astro integration
59
-
60
- `fetchPublicFeed(origin, from, through, category, {locale, strict, publicUrls})` from `@vermeulen.solutions/eventual/astro` validates responses and throws FeedError. **It hardcodes ID `eventual`**; its options do not accept a Registry ID. The showcase has the same assumption. Registry sites need a site-owned adapter to the actual URL or EmDash's SSR dispatcher:
61
-
62
- ```ts
63
- const pluginId = 'YOUR_INSTALLED_PLUGIN_ID';
64
- const url = new URL(`/_emdash/api/plugins/${pluginId}/publicEvents`, Astro.url);
65
- url.searchParams.set('from', '2026-11-01');
66
- url.searchParams.set('through', '2026-11-30');
67
- url.searchParams.set('locale', 'fr');
68
- const runtime = Astro.locals.emdash;
69
- if (!runtime) throw new Error('EmDash is unavailable');
70
- const result = await runtime.handlePublicPluginApiRoute(
71
- pluginId, 'GET', '/publicEvents', new Request(url),
72
- );
73
- if (!result.success) throw new Error(result.error?.message ?? 'Event feed unavailable');
74
- // Validate result.data.ok and result.data.events before rendering.
75
- ```
76
-
77
- `@vermeulen.solutions/eventual/astro/EventList.astro` is an optional unstyled list. JSON-LD helpers are eventToJsonLd and serializeJsonLd; use the safe serializer. The [showcase](../examples/astro-events/README.md) supplies seven complete visitor layouts.
78
-
79
- ## Settings, tools and transfer
80
-
81
- Tools `getSettings` and `updateSettings` use `mcp/settings/get` and `mcp/settings/update`. **updateSettings requires defaultTimezone**, even when only changing legacyReads. Read and retain its value first:
82
-
83
- ```json
84
- {"defaultTimezone":"Europe/Paris","legacyReads":false}
85
- ```
86
-
87
- Optional collections contains `{events,venues,organizers}`. Native timezone defaults belong to the schema. Only stored boolean true enables legacy public reads. Native collections stay authoritative; broken explicit bindings always error. Both MCP and admin `save-legacy-reads` invalidate the request memo.
88
-
89
- Enable intended tools under the plugin's **Agent access** controls. Eventual tools require plugins:manage; native editing uses core content tools and content:edit_any. Read tools: listEvents, getEvent, listOccurrences, listVenues, listOrganizers. Legacy writes are blocked once native collections are active. [Tool schemas](https://github.com/Vermeulen-Solutions/eventual-emdash-sandbox/blob/main/src/mcp-schemas.ts) define exact inputs/routes.
90
-
91
- exportRecords follows cursors (default 5, maximum 10). Native native-content-v1 exports are inspection records, not full backups or legacy-import input. previewImport/importRecords accept legacy data only: at most 10 rows / 64 KiB, insert absent IDs, and import events as drafts. The [@vermeulen.solutions/eventual/transfer interface](../transfer/index.d.mts) supplies legacy backup/copy/CSV/ICS helpers. CSV needs stable source IDs and explicit-offset timed dates; all-day ends are inclusive. ICS conversion accepts standalone UTC or VALUE=DATE events and rejects unsupported recurrence/timezone constructs. Media, settings, revisions and calendar-state recovery need the host's backup facilities.
92
-
93
- ## Limits and checks
94
-
95
- The host's ten-bridge-call budget can constrain feeds, dependency checks and migration even with few displayed events. Smaller date windows or publicUrls=false help some JSON requests; complete-source scans still cost calls. Native exceptions/occurrence copy are bounded at 500 items; calendar group/state/output bounds also apply and fail explicitly. Background migration jobs and bulk APIs remain pending: [Eventual #5](https://github.com/Vermeulen-Solutions/eventual-emdash-sandbox/issues/5), [EmDash #4004](https://github.com/emdash-cms/emdash/issues/4004).
96
-
97
- Calendar UIDs, monotonic SEQUENCE and 366-day cancellation retention support reconciliation. Preserve migrated calendar_uid values. Publication shares schedule fields across languages; pending drafts stay separate. Stale-form checks are not an atomic write lock. Some settings copy remains English in the French admin; stock development-renderer diagnostics are recorded in acceptance.
98
-
99
- Runtime checks: npm run validate, typecheck, build, bundle, budget, and npm test. Tooling/package/editor/media changes have test:tooling, test:package, test:editor and registry:media checks. `node scripts/audit-documentation.mjs` checks local links and Registry section caps. Publishing uses the pinned CLI; immutable releases and current profile/release CIDs need separate approvals. [Release evidence](../audit/releases/0.14.0/README.md).
1
+ # Developer guide — Eventual 0.15.0
2
+
3
+ EmDash collections own content, rich text, languages, drafts, revisions and publication. Eventual's sandbox supplies schedule validation, recurrence, saved-entry controls and feeds. See [setup](collection-setup.md) and [upgrading](upgrade-0.13.0.md).
4
+
5
+ The [public feed caching guide](public-feed-caching.md) describes additive
6
+ dependency/expiry metadata, direct runtime dispatch and the host's explicit opt-in.
7
+
8
+ ## Installation and plugin ID
9
+
10
+ Registry installations use the host's sandbox runner and downloaded bundle. Config-managed installations register the source descriptor in `sandboxed: [eventual]`. Use one backend per site. Cloudflare Registry hosts need Worker Loader and PluginBridge: [EmDash sandbox setup](https://docs.emdashcms.com/deployment/plugin-sandbox/).
11
+
12
+ **Use the installed plugin ID in URLs and MCP names.** Config-managed installs normally use `eventual`; Registry installs have generated IDs such as `r_hxn32uyal53iahxf`. Read it from the install result or authenticated `GET /_emdash/api/admin/plugins`. MCP names are `<pluginId>__<toolName>`.
13
+
14
+ Astro/schema/transfer helpers come from the npm package
15
+ [`@vermeulen.solutions/eventual`](https://www.npmjs.com/package/@vermeulen.solutions/eventual)
16
+ (0.18.1 and later), not the Registry `.tar.gz`. Install the version that matches the Registry backend:
17
+
18
+ ```sh
19
+ npm install @vermeulen.solutions/eventual@0.18.1
20
+ ```
21
+
22
+ Import it as `@vermeulen.solutions/eventual/astro`, `@vermeulen.solutions/eventual/schema` and so on; the plugin ID stays `eventual`.
23
+ Releases before 0.18.1 were not on npm; their source archives (`eventual-<version>.tgz`) are attached to the GitHub releases.
24
+
25
+ To build the same helpers from the release checkout, run `npm ci`, `npm run build`
26
+ and `npm pack`. Keep helper and backend versions aligned.
27
+
28
+ Source tooling needs Node 24+. Peer ranges are in [package.json](../package.json); release acceptance uses EmDash/Admin/Block Kit **1.2.0 and 1.4.0**, Astro 7.3.x/7.4.x and React 19. The source `@vermeulen.solutions/eventual/install` lane accepts 1.2.0 and 1.4.0; Registry installs never execute that transform.
29
+
30
+ | Host | Status | Notes |
31
+ | --- | --- | --- |
32
+ | 1.2.0 | supported, unit-tested | Panel Enter/validation is scoped to the outer content-editor form; Cloudflare cross-isolate plugin mutations can fail. |
33
+ | 1.3.x | supported, untested | Same form/Cloudflare limitations; includes the plugin-storage cursor fix. |
34
+ | 1.4.x | supported, full acceptance | Recommended. Fixes nested Block Kit forms and Cloudflare plugin mutations. |
35
+
36
+ ## Public routes
37
+
38
+ Routes are relative to `/_emdash/api/plugins/<pluginId>/`.
39
+
40
+ | Route | Inputs and behavior |
41
+ | --- | --- |
42
+ | `GET publicEvents` | Inclusive `from`/`through` dates (YYYY-MM-DD); default UTC today through 180 days later; maximum 366 inclusive dates. Also `locale`, `strict` (false), `category`, `publicUrls` (true). |
43
+ | `GET calendar` | Raw text/calendar; fixed window from UTC today through 365 days later. Supports locale, strict and category. |
44
+ | `GET publicEventImage?eventId=…` | Published featured image with MIME/size checks; absent, unpublished or disabled legacy images return 404. |
45
+
46
+ `strict=true` omits events without the requested translation; false can use another language with a `[FR]`/`[EN]` title prefix. Categories match without case sensitivity. `publicUrls=false` skips native canonical-URL lookups; slug/id remain available for site-owned links.
47
+
48
+ JSON success:
49
+
50
+ ```json
51
+ {"success":true,"data":{"ok":true,"from":"2026-11-01","through":"2026-11-30","events":[]}}
52
+ ```
53
+
54
+ The feed has no top-level locale. Event rows carry title, description/plain text, optional descriptionBlocks, start/end, allDay, timezone, location, organizer, externalUrl, imageUrl, categories, venue and directionsUrl. Optional native metadata includes locale, translationGroup, slug and publicUrl. Business status is `status`, not `eventStatus`: see [PublicEvent](../src/public-event.ts). All-day end dates are inclusive here and exclusive in ICS.
55
+
56
+ Handle both `success:false` host failures and `data.ok:false` plugin failures. EmDash 1.2.0 JSON configuration/RPC failures use HTTP 400, ROUTE_ERROR and private/no-store caching. Preserve errors instead of substituting stale rows or a successful empty feed.
57
+
58
+ ## Astro integration
59
+
60
+ `fetchPublicFeed(origin, from, through, category, {locale, strict, publicUrls})` from `@vermeulen.solutions/eventual/astro` validates responses and throws FeedError. **It hardcodes ID `eventual`**; its options do not accept a Registry ID. The showcase has the same assumption. Registry sites need a site-owned adapter to the actual URL or EmDash's SSR dispatcher:
61
+
62
+ ```ts
63
+ const pluginId = 'YOUR_INSTALLED_PLUGIN_ID';
64
+ const url = new URL(`/_emdash/api/plugins/${pluginId}/publicEvents`, Astro.url);
65
+ url.searchParams.set('from', '2026-11-01');
66
+ url.searchParams.set('through', '2026-11-30');
67
+ url.searchParams.set('locale', 'fr');
68
+ const runtime = Astro.locals.emdash;
69
+ if (!runtime) throw new Error('EmDash is unavailable');
70
+ const result = await runtime.handlePublicPluginApiRoute(
71
+ pluginId, 'GET', '/publicEvents', new Request(url),
72
+ );
73
+ if (!result.success) throw new Error(result.error?.message ?? 'Event feed unavailable');
74
+ // Validate result.data.ok and result.data.events before rendering.
75
+ ```
76
+
77
+ `@vermeulen.solutions/eventual/astro/EventList.astro` is an optional unstyled list. JSON-LD helpers are eventToJsonLd and serializeJsonLd; use the safe serializer. The [showcase](../examples/astro-events/README.md) supplies seven complete visitor layouts.
78
+
79
+ ## Settings, tools and transfer
80
+
81
+ Tools `getSettings` and `updateSettings` use `mcp/settings/get` and `mcp/settings/update`. **updateSettings requires defaultTimezone**, even when only changing legacyReads. Read and retain its value first:
82
+
83
+ ```json
84
+ {"defaultTimezone":"Europe/Paris","legacyReads":false}
85
+ ```
86
+
87
+ Optional collections contains `{events,venues,organizers}`. Native timezone defaults belong to the schema. Only stored boolean true enables legacy public reads. Native collections stay authoritative; broken explicit bindings always error. Both MCP and admin `save-legacy-reads` invalidate the request memo.
88
+
89
+ Enable intended tools under the plugin's **Agent access** controls. Eventual tools require plugins:manage; native editing uses core content tools and content:edit_any. Read tools: listEvents, getEvent, listOccurrences, listVenues, listOrganizers. Legacy writes are blocked once native collections are active. [Tool schemas](https://github.com/Vermeulen-Solutions/eventual-rsvp-core/blob/main/src/mcp-schemas.ts) define exact inputs/routes.
90
+
91
+ exportRecords follows cursors (default 5, maximum 10). Native native-content-v1 exports are inspection records, not full backups or legacy-import input. previewImport/importRecords accept legacy data only: at most 10 rows / 64 KiB, insert absent IDs, and import events as drafts. The [@vermeulen.solutions/eventual/transfer interface](../transfer/index.d.mts) supplies legacy backup/copy/CSV/ICS helpers. CSV needs stable source IDs and explicit-offset timed dates; all-day ends are inclusive. ICS conversion accepts standalone UTC or VALUE=DATE events and rejects unsupported recurrence/timezone constructs. Media, settings, revisions and calendar-state recovery need the host's backup facilities.
92
+
93
+ ## Limits and checks
94
+
95
+ The host's ten-bridge-call budget can constrain feeds, dependency checks and migration even with few displayed events. Smaller date windows or publicUrls=false help some JSON requests; complete-source scans still cost calls. Native exceptions/occurrence copy are bounded at 500 items; calendar group/state/output bounds also apply and fail explicitly. Background migration jobs and bulk APIs remain pending: [Eventual #5](https://github.com/Vermeulen-Solutions/eventual-rsvp-core/issues/5), [EmDash #4004](https://github.com/emdash-cms/emdash/issues/4004).
96
+
97
+ Calendar UIDs, monotonic SEQUENCE and 366-day cancellation retention support reconciliation. Preserve migrated calendar_uid values. Publication shares schedule fields across languages; pending drafts stay separate. Stale-form checks are not an atomic write lock. Some settings copy remains English in the French admin; stock development-renderer diagnostics are recorded in acceptance.
98
+
99
+ Runtime checks: npm run validate, typecheck, build, bundle, budget, and npm test. Tooling/package/editor/media changes have test:tooling, test:package, test:editor and registry:media checks. `node scripts/audit-documentation.mjs` checks local links and Registry section caps. Publishing uses the pinned CLI; immutable releases and current profile/release CIDs need separate approvals. [Release evidence](../audit/releases/0.14.0/README.md).
@@ -1,13 +1,13 @@
1
- # Eventual RSVP – Core 0.18.1
2
-
3
- Requires EmDash **>=1.2.0 <2.0.0** for event management. **1.4.0 is recommended** for nested forms and Cloudflare plugin mutations, and required for the optional cache integration.
4
-
5
- In **Plugins → Registry**, find **Eventual RSVP – Core** by **vermeulen.solutions**, review permissions and install or update. Version 0.18.1 asks for no new permissions; since 0.18.0 Core uses `network:request` to `cdn.jsdelivr.net` for the admin's language packs. It adds no MCP tools. Enable intended tools separately under **Agent access**.
6
-
7
- Open **Event settings**, select compatible event, venue and organizer collections, then **Save settings**. Installation does not create schemas or migrate content. Site builders: [collection setup](https://github.com/Vermeulen-Solutions/eventual-emdash-sandbox/blob/main/docs/collection-setup.md).
8
-
9
- Save an announcement, open **Dates, venue & repeat**, save changed sections, reload, then publish in EmDash. [Editor guide](https://github.com/Vermeulen-Solutions/eventual-emdash-sandbox/blob/main/docs/user-guide.md).
10
-
11
- Keep **Show old events saved inside the plugin** off for native collections. Enable it only to serve legacy plugin data without a connected collection. Upgrades from 0.12.x or earlier need a backup and [native migration](https://github.com/Vermeulen-Solutions/eventual-emdash-sandbox/blob/main/docs/upgrade-0.13.0.md).
12
-
13
- Your site builder connects visitor pages, optionally with the npm helpers `@vermeulen.solutions/eventual` at the same version. **Caching stays opt-in**: Core supplies dependencies and a maximum 15-second expiry, not site-wide cache rules. Use matching source helpers, explicit eligibility and no stale serving. Read the [integration guide and host limitations](https://github.com/Vermeulen-Solutions/eventual-emdash-sandbox/blob/main/docs/public-feed-caching.md) before enabling it.
1
+ # Eventual RSVP – Core 0.18.2
2
+
3
+ Requires EmDash **>=1.2.0 <2.0.0** for event management. **1.4.0 is recommended** for nested forms and Cloudflare plugin mutations, and required for the optional cache integration.
4
+
5
+ In **Plugins → Registry**, find **Eventual RSVP – Core** by **vermeulen.solutions**, review permissions and install or update. Version 0.18.2 asks for no new permissions; since 0.18.0 Core uses `network:request` to `cdn.jsdelivr.net` for the admin's language packs. It adds no MCP tools. Enable intended tools separately under **Agent access**.
6
+
7
+ Open **Event settings**, select compatible event, venue and organizer collections, then **Save settings**. Installation does not create schemas or migrate content. Site builders: [collection setup](https://github.com/Vermeulen-Solutions/eventual-rsvp-core/blob/main/docs/collection-setup.md).
8
+
9
+ Save an announcement, open **Dates, venue & repeat**, save changed sections, reload, then publish in EmDash. [Editor guide](https://github.com/Vermeulen-Solutions/eventual-rsvp-core/blob/main/docs/user-guide.md).
10
+
11
+ Keep **Show old events saved inside the plugin** off for native collections. Enable it only to serve legacy plugin data without a connected collection. Upgrades from 0.12.x or earlier need a backup and [native migration](https://github.com/Vermeulen-Solutions/eventual-rsvp-core/blob/main/docs/upgrade-0.13.0.md).
12
+
13
+ Your site builder connects visitor pages, optionally with the npm helpers `@vermeulen.solutions/eventual` at the same version. **Caching stays opt-in**: Core supplies dependencies and a maximum 15-second expiry, not site-wide cache rules. Use matching source helpers, explicit eligibility and no stale serving. Read the [integration guide and host limitations](https://github.com/Vermeulen-Solutions/eventual-rsvp-core/blob/main/docs/public-feed-caching.md) before enabling it.
@@ -1,40 +1,40 @@
1
- # Eventual 0.14.1
2
-
3
- Released 30 October 2026. Requires EmDash **>=1.2.0 <2.0.0**.
4
-
5
- This is a compatibility release. It changes no runtime API, capability, schema, route or MCP tool. Existing sites need no data migration.
6
-
7
- ## Host compatibility
8
-
9
- | EmDash | Status | Notes |
10
- | --- | --- | --- |
11
- | 1.2.0 | Supported, unit-tested | The schedule panel's Enter key and validation are scoped to the surrounding entry form; Cloudflare plugin mutations can fail across Worker isolates. |
12
- | 1.3.x | Supported, untested | Same form and Cloudflare limitations. Includes the plugin-storage cursor fix. |
13
- | 1.4.x | Supported, full acceptance | Recommended. Fixes nested Block Kit forms and Cloudflare plugin mutations. |
14
-
15
- **Use EmDash 1.4.0 or later for the corrected schedule-panel form behaviour and reliable create/publish across Cloudflare Worker isolates.** The Registry install range stays `>=1.2.0 <2.0.0`; 1.2/1.3 remain installable but retain the host limitations above.
16
-
17
- ## What changed
18
-
19
- - The source `eventual/install` editor transform handles both Block Kit renderers:
20
- - 1.2/1.3 render plugin forms as `<form>` inside the content editor's form.
21
- - 1.4 renders `div[role="group"]` with its own Enter handling.
22
- - The transform keeps Eventual's form-value resync, stable field keys and date-label association, which the host renderer does not provide.
23
- - The source editor version gate accepts EmDash/Admin/Block Kit 1.2.0 and 1.4.0.
24
- - The local test site is on EmDash 1.4.0 and now runs a native-collection gate in development and production.
25
-
26
- Registry installs never execute the source transform; their rendering comes from the host's `@emdash-cms/blocks`. That is why the 1.4.0 host upgrade, not a Registry-time patch, delivers the form fix.
27
-
28
- ## Verification
29
-
30
- - Full plugin suite on EmDash 1.2.0 and 1.4.0: 26 files, 228 tests, plus 24 tooling tests.
31
- - Packed-consumer packaging and editor acceptance on EmDash 1.4.0.
32
- - Local test site on EmDash 1.4.0 in development and production: plugin registration, MCP consent, admin pages/widget, public feed, event detail and JSON-LD, per-event ICS, native `getEvent`, and draft duplication through native content creation (six groups).
33
-
34
- ### Known limitation
35
-
36
- The full-year calendar subscription can exceed EmDash's ten-bridge-call sandbox budget on a larger native dataset. The local 1.4.0 site recorded a 503 for `/_emdash/api/plugins/eventual/calendar` with five native events; the JSON feed and per-event ICS route were unaffected. Narrower feeds, background jobs and bulk APIs remain open work ([Eventual #5](https://github.com/Vermeulen-Solutions/eventual-emdash-sandbox/issues/5), [EmDash #4004](https://github.com/emdash-cms/emdash/issues/4004)).
37
-
38
- ## Upgrade
39
-
40
- Update normally in **Plugins → Registry**. No capability consent, schema or data change is required. Sites on EmDash 1.2/1.3 can update Eventual but should upgrade EmDash to 1.4.0 for the form and Cloudflare fixes. Earlier Eventual versions still need the [native-content upgrade](upgrade-0.13.0.md).
1
+ # Eventual 0.14.1
2
+
3
+ Released 30 October 2026. Requires EmDash **>=1.2.0 <2.0.0**.
4
+
5
+ This is a compatibility release. It changes no runtime API, capability, schema, route or MCP tool. Existing sites need no data migration.
6
+
7
+ ## Host compatibility
8
+
9
+ | EmDash | Status | Notes |
10
+ | --- | --- | --- |
11
+ | 1.2.0 | Supported, unit-tested | The schedule panel's Enter key and validation are scoped to the surrounding entry form; Cloudflare plugin mutations can fail across Worker isolates. |
12
+ | 1.3.x | Supported, untested | Same form and Cloudflare limitations. Includes the plugin-storage cursor fix. |
13
+ | 1.4.x | Supported, full acceptance | Recommended. Fixes nested Block Kit forms and Cloudflare plugin mutations. |
14
+
15
+ **Use EmDash 1.4.0 or later for the corrected schedule-panel form behaviour and reliable create/publish across Cloudflare Worker isolates.** The Registry install range stays `>=1.2.0 <2.0.0`; 1.2/1.3 remain installable but retain the host limitations above.
16
+
17
+ ## What changed
18
+
19
+ - The source `eventual/install` editor transform handles both Block Kit renderers:
20
+ - 1.2/1.3 render plugin forms as `<form>` inside the content editor's form.
21
+ - 1.4 renders `div[role="group"]` with its own Enter handling.
22
+ - The transform keeps Eventual's form-value resync, stable field keys and date-label association, which the host renderer does not provide.
23
+ - The source editor version gate accepts EmDash/Admin/Block Kit 1.2.0 and 1.4.0.
24
+ - The local test site is on EmDash 1.4.0 and now runs a native-collection gate in development and production.
25
+
26
+ Registry installs never execute the source transform; their rendering comes from the host's `@emdash-cms/blocks`. That is why the 1.4.0 host upgrade, not a Registry-time patch, delivers the form fix.
27
+
28
+ ## Verification
29
+
30
+ - Full plugin suite on EmDash 1.2.0 and 1.4.0: 26 files, 228 tests, plus 24 tooling tests.
31
+ - Packed-consumer packaging and editor acceptance on EmDash 1.4.0.
32
+ - Local test site on EmDash 1.4.0 in development and production: plugin registration, MCP consent, admin pages/widget, public feed, event detail and JSON-LD, per-event ICS, native `getEvent`, and draft duplication through native content creation (six groups).
33
+
34
+ ### Known limitation
35
+
36
+ The full-year calendar subscription can exceed EmDash's ten-bridge-call sandbox budget on a larger native dataset. The local 1.4.0 site recorded a 503 for `/_emdash/api/plugins/eventual/calendar` with five native events; the JSON feed and per-event ICS route were unaffected. Narrower feeds, background jobs and bulk APIs remain open work ([Eventual #5](https://github.com/Vermeulen-Solutions/eventual-rsvp-core/issues/5), [EmDash #4004](https://github.com/emdash-cms/emdash/issues/4004)).
37
+
38
+ ## Upgrade
39
+
40
+ Update normally in **Plugins → Registry**. No capability consent, schema or data change is required. Sites on EmDash 1.2/1.3 can update Eventual but should upgrade EmDash to 1.4.0 for the form and Cloudflare fixes. Earlier Eventual versions still need the [native-content upgrade](upgrade-0.13.0.md).
@@ -0,0 +1,6 @@
1
+ # Eventual RSVP – Core 0.18.2 — registry page
2
+
3
+ - **New registry screenshots**: the event editor with **Dates, venue & repeat**, the public calendar, an event page, and **Event settings**.
4
+ - **Registry description tab** with links to [eventual.rsvp](https://eventual.rsvp/), the documentation, the install guide and support.
5
+ - **Setup guide link**: the button on the Event settings page now points to [github.com/Vermeulen-Solutions/eventual-rsvp-core](https://github.com/Vermeulen-Solutions/eventual-rsvp-core), the repository's new name. The old address redirects.
6
+ - **Nothing else changes**: no runtime, permission or schema changes, and no new MCP tools. EmDash `>=1.2.0 <2.0.0` (tested on EmDash 1.4.0).
@@ -5,27 +5,27 @@
5
5
  "publisher": "did:plc:g2hei4vcwndrdl3gdbb6np6c", // vermeulen.solutions
6
6
 
7
7
  "license": "MIT",
8
- "author": { "name": "Jaap Vermeulen", "email": "support@eventual.rsvp" },
8
+ "author": { "name": "Jaap Vermeulen", "url": "https://eventual.rsvp/", "email": "support@eventual.rsvp" },
9
9
  "security": { "email": "security@eventual.rsvp" },
10
10
  "name": "Eventual RSVP – Core",
11
11
  "description": "Native EmDash events with rich text, localization, friendly recurrence, saved venues and multilingual calendar feeds.",
12
12
  "keywords": ["events", "calendar", "event management", "iCalendar", "venues"],
13
13
  "sections": {
14
+ "description": { "file": "./docs/registry-description.md" },
14
15
  "installation": { "file": "./docs/registry-installation.md" },
15
16
  "changelog": { "file": "./docs/registry-changelog.md" }
16
17
  },
17
- "repo": "https://github.com/Vermeulen-Solutions/eventual-emdash-sandbox",
18
+ "repo": "https://github.com/Vermeulen-Solutions/eventual-rsvp-core",
18
19
  "release": {
19
20
  "requires": { "env:emdash": ">=1.2.0 <2.0.0" },
20
21
  "artifacts": {
21
22
  "icon": { "file": "./images/registry/icon-v2.png" },
22
23
  "banner": { "file": "./images/registry/banner-v2.png" },
23
24
  "screenshots": [
24
- { "file": "./images/registry-0.13.0/native-fr-editor-desktop.png" },
25
- { "file": "./images/registry-0.14.0/native-fr-settings.png" },
26
- { "file": "./images/registry-0.13.0/native-en-workspace-mobile.png" },
27
- { "file": "./images/registry-0.11.0/05-public-events.jpg" },
28
- { "file": "./images/registry-0.13.4/public-event-detail-fr-desktop.png" }
25
+ { "file": "./images/registry/screenshots-v1/1-event-editor.png" },
26
+ { "file": "./images/registry/screenshots-v1/2-public-calendar.png" },
27
+ { "file": "./images/registry/screenshots-v1/3-event-page.png" },
28
+ { "file": "./images/registry/screenshots-v1/4-settings.png" }
29
29
  ]
30
30
  }
31
31
  },
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@vermeulen.solutions/eventual",
3
- "version": "0.18.1",
3
+ "version": "0.18.2",
4
4
  "license": "MIT",
5
- "homepage": "https://plugins.emdashcms.com/plugins/@vermeulen.solutions/eventual",
5
+ "homepage": "https://eventual.rsvp/",
6
6
  "type": "module",
7
7
  "engines": {
8
8
  "node": ">=24"
@@ -63,7 +63,8 @@
63
63
  "docs/release-notes-0.16.0.md",
64
64
  "docs/release-notes-0.17.0.md",
65
65
  "docs/release-notes-0.18.0.md",
66
- "docs/release-notes-0.18.1.md"
66
+ "docs/release-notes-0.18.1.md",
67
+ "docs/release-notes-0.18.2.md"
67
68
  ],
68
69
  "scripts": {
69
70
  "validate": "emdash-plugin validate",