@vermeulen.solutions/eventual 0.18.5 → 0.18.7

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/dist/plugin.mjs CHANGED
@@ -1,13 +1,13 @@
1
- function e(e={}){let t=[];return new Headers(e.headers).forEach((e,n)=>t.push([n,e])),{__emdashPluginResponse:!0,status:e.status??200,headers:t,body:e.body??null}}function t(e){return e}const n=`Enter a valid IANA timezone, such as Europe/Paris.`,r=`External URL must use HTTP or HTTPS.`;function i(e){throw Error(e)}const a=e=>typeof e==`string`?e:``;function o(e,t){let n=new Date(0);return n.setUTCFullYear(e,t,0),n.getUTCDate()}function s(e){let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;let n=Number(t[1]),r=Number(t[2]),i=Number(t[3]);return r<1||r>12||i<1||i>o(n,r)?null:{year:n,month:r,day:i,hour:0,minute:0}}function c(e){let t=/^(\d{4}-\d{2}-\d{2})T(\d{2}):(\d{2})$/.exec(e),n=t?s(t[1]):null;if(!n||!t)return null;let r=Number(t[2]),i=Number(t[3]);return r>23||i>59?null:{...n,hour:r,minute:i}}const l=new Map;function u(e,t){try{let n=l.get(t);n||(n=new Intl.DateTimeFormat(`en`,{timeZone:t,calendar:`gregory`,numberingSystem:`latn`,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`}),l.size>=128&&l.delete(l.keys().next().value),l.set(t,n));let r=n.formatToParts(e),i=e=>Number(r.find(t=>t.type===e)?.value),a={year:i(`year`),month:i(`month`),day:i(`day`),hour:i(`hour`),minute:i(`minute`)};return Object.values(a).every(Number.isFinite)?a:null}catch{return null}}function d(e){let t=new Date(0);return t.setUTCFullYear(e.year,e.month-1,e.day),t.setUTCHours(e.hour,e.minute,0,0),t.getTime()}function f(e,t){return e.year===t.year&&e.month===t.month&&e.day===t.day&&e.hour===t.hour&&e.minute===t.minute}function p(e){return s(e)!==null}function m(e,t){let n=new Date(`${e}T00:00:00Z`);return n.setUTCDate(n.getUTCDate()+t),n.toISOString().slice(0,10)}function h(e){if(!e.trim())return!1;try{return new Intl.DateTimeFormat(`en`,{timeZone:e}),!0}catch{return!1}}function g(e,t){let r=c(e);if(!r)return{error:`Enter a valid date and time.`};if(!h(t))return{error:n};let i=d(r),a=new Set,o=!1;for(let e=-36;e<=36;e+=3){let n=i+e*36e5,s=u(new Date(n),t);if(!s)continue;o=!0;let c=i-(d(s)-n),l=u(new Date(c),t);l&&f(l,r)&&a.add(c)}return o?a.size?{value:new Date(Math.min(...a)).toISOString()}:{error:`That local time does not exist because of a daylight-saving change.`}:{error:`The selected timezone could not be applied.`}}function _(e,t){let n=new Date(e);if(Number.isNaN(n.getTime())||!h(t))return``;let r=u(n,t);if(!r)return``;let i=e=>String(e).padStart(2,`0`);return`${String(r.year).padStart(4,`0`)}-${i(r.month)}-${i(r.day)}T${i(r.hour)}:${i(r.minute)}`}function v(e,t,n){if(t)return p(e)?e:``;let r=new Date(e);if(Number.isNaN(r.getTime()))return``;let i=u(r,h(n)?n:`UTC`);return i?`${String(i.year).padStart(4,`0`)}-${String(i.month).padStart(2,`0`)}-${String(i.day).padStart(2,`0`)}`:``}function y(e){let t={};if(e.allDay)return p(e.start)||(t.start=`Choose a valid start date.`),p(e.end)||(t.end=`Choose a valid end date.`),!t.start&&!t.end&&e.end<e.start&&(t.end=`The end must be on or after the start.`),Object.keys(t).length?{errors:t}:{dates:{start:e.start,end:e.end},errors:t};if(!h(e.timezone))return t.timezone=n,{errors:t};let r=g(e.start,e.timezone),i=g(e.end,e.timezone);return r.value||(t.start=r.error),i.value||(t.end=i.error),r.value&&i.value&&Date.parse(i.value)<Date.parse(r.value)&&(t.end=`The end must be on or after the start.`),Object.keys(t).length?{errors:t}:{dates:{start:r.value,end:i.value},errors:t}}function b(e){let t=typeof e==`string`?e.split(/[,\r\n]+/):e,n=[],r=new Set;for(let e of t){let t=e.trim().replace(/\s+/g,` `);if(!t)continue;let i=t.toLowerCase();r.has(i)||(r.add(i),n.push(t))}return n}function x(e){return e.trim().replace(/\s+/g,` `).toLowerCase()}function S(e){return e==null||e===``?[]:(typeof e==`string`&&e.trim().startsWith(`[`)&&(e=JSON.parse(e)),typeof e==`string`||(!Array.isArray(e)||e.some(e=>typeof e!=`string`))&&i(`Categories must be comma-separated text or an array of names.`),b(e))}function C(e){return[e.street,e.street2,e.locality,e.region,e.postalCode,e.country].map(e=>e?.trim()).filter(Boolean).join(`, `)}function w(e,t){return[e?.name,e?C(e):``,t.trim()].filter(Boolean).join(` · `)}function T(e){let t=e.trim();if(!t)return``;let n=`https://www.google.com/maps/dir/?api=1&destination=${encodeURIComponent(t)}`;return n.length<=2048?n:``}function E(e){if(typeof e!=`string`||!e.trim())return``;try{let t=new URL(e);return t.hostname&&(t.protocol===`http:`||t.protocol===`https:`)?t.href:``}catch{return``}}const D=[`sunday`,`monday`,`tuesday`,`wednesday`,`thursday`,`friday`,`saturday`];function O(e){if(!e||typeof e!=`object`)return!1;let t=e;if(typeof t.until!=`string`||!p(t.until)||t.interval!==void 0&&(typeof t.interval!=`number`||!Number.isInteger(t.interval)||t.interval<1||t.interval>52))return!1;if(t.frequency===`daily`)return t.weekdays===void 0;if(t.frequency===`weekly`)return t.weekdays===void 0||Array.isArray(t.weekdays)&&t.weekdays.length>=1&&t.weekdays.length<=7&&new Set(t.weekdays).size===t.weekdays.length&&t.weekdays.every(e=>D.includes(e));if(t.frequency!==`monthly`||!t.pattern||typeof t.pattern!=`object`)return!1;let n=t.pattern;return n.type===`dayOfMonth`?Number.isInteger(n.dayOfMonth)&&Number(n.dayOfMonth)>=1&&Number(n.dayOfMonth)<=31&&(n.missingDayBehavior===`skip`||n.missingDayBehavior===`lastDay`):n.type===`weekdayOfMonth`&&D.includes(n.weekday)&&(n.position===`last`||Number.isInteger(n.position)&&Number(n.position)>=1&&Number(n.position)<=5)}function ee(e){let t=e.interval??1;return e.frequency===`weekly`&&e.weekdays?`every ${t===1?`week`:`${t} weeks`} on ${e.weekdays.map(e=>e[0].toUpperCase()+e.slice(1)).join(`, `)}`:t===1?e.frequency:`every ${t} ${e.frequency===`daily`?`days`:e.frequency===`weekly`?`weeks`:`months`}`}function te(e){return[...e].sort((e,t)=>(D.indexOf(e)+6)%7-(D.indexOf(t)+6)%7)}const ne=[`sunday`,`monday`,`tuesday`,`wednesday`,`thursday`,`friday`,`saturday`];function re(e){return e.slice(0,10).split(`-`).map(Number)}function ie(e){let[t,n,r]=re(e);return ne[new Date(Date.UTC(t,n-1,r)).getUTCDay()]}function ae(e){let[,,t]=re(e);return Math.ceil(t/7)}function oe(e){let[t,n,r]=re(e),i=new Date(Date.UTC(t,n-1,r+7));return i.getUTCMonth()!==n-1||i.getUTCFullYear()!==t}function se(e){if(e.repeatFrequency===`none`)return;let t={until:e.recurrenceUntil,...e.recurrenceInterval!==void 0&&e.recurrenceInterval!==1?{interval:e.recurrenceInterval}:{}};return e.repeatFrequency===`daily`||e.repeatFrequency===`weekly`?{frequency:e.repeatFrequency,...t,...e.repeatFrequency===`weekly`&&e.weeklyWeekdays?.length?{weekdays:te(e.weeklyWeekdays)}:{}}:{frequency:`monthly`,...t,pattern:e.monthlyPattern===`dayOfMonth`?{type:`dayOfMonth`,dayOfMonth:e.monthlyDayOfMonth??Number(e.start.slice(8,10)),missingDayBehavior:e.missingDayBehavior}:{type:`weekdayOfMonth`,weekday:e.monthlyWeekday,position:e.monthlyPosition}}}function ce(e,t){return e?!t||t===`draft`?`published`:t:`draft`}function le(e,t){let n=e.title.trim();if(!n)return{error:`Event title is required.`};if(e.externalUrl.trim()&&!E(e.externalUrl))return{error:r};if(e.virtualUrl?.trim()&&!E(e.virtualUrl))return{error:`Virtual URL must use HTTP or HTTPS.`};if(e.imageUrl.trim()&&!E(e.imageUrl))return{error:`Image URL must use HTTP or HTTPS.`};let i=t?{dates:t,errors:{}}:y({start:e.start,end:e.end,allDay:e.allDay,timezone:e.timezone});if(!i.dates)return{error:i.errors.start??i.errors.end??i.errors.timezone??`Check the event dates.`};let a=e.start.slice(0,10),o=se(e);if(o&&!O(o))return{error:`Choose a valid repeat pattern and an integer interval from 1 through 52.`};if(o?.frequency===`weekly`&&o.weekdays&&!o.weekdays.includes(ie(a)))return{error:`The first event must fall on one of the selected weekly days.`};if(o&&(!p(o.until)||o.until<a))return{error:`Choose a recurrence end date on or after the first event.`};if(o?.frequency===`monthly`&&o.pattern.type===`weekdayOfMonth`&&(ie(a)!==o.pattern.weekday||(o.pattern.position===`last`?!oe(a):ae(a)!==o.pattern.position)))return{error:`The first event must match the selected monthly weekday pattern.`};if(o?.frequency===`monthly`&&o.pattern.type===`dayOfMonth`){let[e,t,n]=re(a),r=new Date(Date.UTC(e,t,0)).getUTCDate();if(n!==(o.pattern.missingDayBehavior===`lastDay`?Math.min(o.pattern.dayOfMonth,r):o.pattern.dayOfMonth))return{error:`The first event must match the selected monthly day and missing-day policy.`}}let s=b(e.categories),c=(e.featuredMediaId||e.imageMediaId||``).trim();return{data:{title:n,description:e.description.trim(),...i.dates,allDay:e.allDay,timezone:e.timezone.trim(),location:e.location.trim(),locationType:e.locationType??`physical`,...e.virtualUrl?.trim()?{virtualUrl:E(e.virtualUrl)}:{},status:ce(e.published,e.status),organizer:e.organizer.trim(),...e.organizerId?{organizerId:e.organizerId}:{},externalUrl:E(e.externalUrl),imageUrl:c?``:E(e.imageUrl),...c?{imageMediaId:c,featuredMediaId:c}:{},categories:s,...e.venueId?{venueId:e.venueId}:{},published:e.published,...o?{recurrence:o}:{},exceptions:e.exceptions}}}function ue(e){let t=e.timezone||`UTC`,n=e.allDay?e.start.slice(0,10):_(e.start,t),r=e.allDay?e.end.slice(0,10):_(e.end,t),i=e.recurrence;return{title:e.title,description:e.description,start:n,end:r,allDay:e.allDay,timezone:t,location:e.location,locationType:e.locationType??`physical`,virtualUrl:e.virtualUrl??``,status:ce(e.published,e.status),organizer:e.organizer,organizerId:e.organizerId,externalUrl:e.externalUrl,imageUrl:e.imageUrl,imageMediaId:e.featuredMediaId??e.imageMediaId??``,featuredMediaId:e.featuredMediaId??e.imageMediaId??void 0,categories:e.categories.join(`, `),venueId:e.venueId??``,published:e.published,repeatFrequency:i?.frequency??`none`,recurrenceUntil:i?.until??``,recurrenceInterval:i?.interval??1,weeklyWeekdays:i?.frequency===`weekly`?i.weekdays:void 0,monthlyDayOfMonth:i?.frequency===`monthly`&&i.pattern.type===`dayOfMonth`?i.pattern.dayOfMonth:Number(n.slice(8,10)),monthlyPattern:i?.frequency===`monthly`?i.pattern.type:`dayOfMonth`,missingDayBehavior:i?.frequency===`monthly`&&i.pattern.type===`dayOfMonth`?i.pattern.missingDayBehavior:`skip`,monthlyWeekday:i?.frequency===`monthly`&&i.pattern.type===`weekdayOfMonth`?i.pattern.weekday:ie(n),monthlyPosition:i?.frequency===`monthly`&&i.pattern.type===`weekdayOfMonth`?i.pattern.position:n?ae(n):1,exceptions:e.exceptions??[]}}const de=[`sunday`,`monday`,`tuesday`,`wednesday`,`thursday`,`friday`,`saturday`];function k(e){let[t,n,r]=e.split(`-`).map(Number);return new Date(Date.UTC(t,n-1,r))}function fe(e){return`${String(e.getUTCFullYear()).padStart(4,`0`)}-${String(e.getUTCMonth()+1).padStart(2,`0`)}-${String(e.getUTCDate()).padStart(2,`0`)}`}function A(e,t){let n=k(e);return n.setUTCDate(n.getUTCDate()+t),fe(n)}function pe(e,t){return(k(t).getTime()-k(e).getTime())/864e5}function me(e){let t=k(e);return Math.ceil(t.getUTCDate()/7)}function he(e,t){if(t.frequency!==`monthly`)return!1;let n=k(e);if(t.pattern.type===`dayOfMonth`){let e=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth()+1,0)).getUTCDate(),r=t.pattern.missingDayBehavior===`lastDay`?Math.min(t.pattern.dayOfMonth,e):t.pattern.dayOfMonth;return n.getUTCDate()===r}if(de[n.getUTCDay()]!==t.pattern.weekday)return!1;if(t.pattern.position!==`last`)return me(e)===t.pattern.position;let r=k(A(e,7));return r.getUTCMonth()!==n.getUTCMonth()||r.getUTCFullYear()!==n.getUTCFullYear()}function ge(e){return e.allDay?e.start.slice(0,10):_(e.start,e.timezone).slice(0,10)}function _e(e,t,n){return n?e:`${e}T${t}`}function ve(e,t){let n=e.recurrence,r=ge(e);if(!n||t<r||t>n.until)return!1;let i=n.interval??1,a=pe(r,t);if(n.frequency===`daily`)return a%i===0;if(n.frequency===`weekly`){let e=Math.floor((a+(k(r).getUTCDay()+6)%7)/7),o=k(t).getUTCDay();return e%i===0&&(n.weekdays?n.weekdays.includes(de[o]):o===k(r).getUTCDay())}let o=k(t),s=k(r);return((o.getUTCFullYear()-s.getUTCFullYear())*12+o.getUTCMonth()-s.getUTCMonth())%i===0&&he(t,n)}function j(e,t){let n=t.slice(0,10);if(!p(n)||!ve(e,n))return null;let r=e.allDay?``:_(e.start,e.timezone).slice(11,16);if(t!==_e(n,r,e.allDay))return null;let i=n,a=A(n,pe(e.start.slice(0,10),e.end.slice(0,10)));if(!e.allDay){let t=g(`${n}T${r}`,e.timezone);if(!t.value)return null;i=t.value,a=new Date(Date.parse(i)+Date.parse(e.end)-Date.parse(e.start)).toISOString()}return be({...e,start:i,end:a},t)}function ye(e,t,n,r){if(e.status!==`modified`||!e.overrides?.start)return!1;let i=e.overrides.start,a=e.overrides.allDay??t.allDay,o=e.overrides.timezone??t.timezone,s=a?i.slice(0,10):v(i,!1,o),c=e.overrides.end??i,l=a?c.slice(0,10):v(c,!1,o);return s<=r&&l>=n}function be(e,t,n){if(n?.status===`cancelled`)return null;let{recurrence:r,exceptions:i,previousStartDate:a,scheduleHistory:o,...s}=e;return{...s,...n?.overrides,...n?.overrides?.start&&n.overrides.start!==e.start?{previousStartDate:e.start}:{},...n?.overrides?.organizer===void 0?{}:{organizerId:void 0,organizerDetails:void 0},...n?.overrides?.description===void 0?{}:{descriptionBlocks:(()=>{let e=n.overrides.description;if(Array.isArray(e))return e;try{let t=JSON.parse(String(e));return Array.isArray(t)?t:void 0}catch{return}})(),description:typeof n.overrides.description==`string`?n.overrides.description:JSON.stringify(n.overrides.description)},status:ce(e.published,n?.overrides?.status??e.status),id:`${e.id}#${t}`,exceptions:[],createdAt:e.createdAt,updatedAt:e.updatedAt}}function xe(e,t,n){let r=v(e.start,e.allDay,e.timezone),i=v(e.end,e.allDay,e.timezone);return r<=n&&i>=t}function Se(e,t,n){let r=e.recurrence;if(!r||!p(t)||!p(n)||t>n||pe(t,n)>=366)return[];let i=ge(e);if(!p(i)||i>r.until)return[];let a=e.allDay?``:_(e.start,e.timezone).slice(11,16),o=Date.parse(e.end)-Date.parse(e.start),s=e.allDay?pe(e.start.slice(0,10),e.end.slice(0,10)):0,c=e.allDay?s:Math.ceil(o/864e5),l=A(t,-Math.min(366,c)),u=n<r.until?n:r.until,d=new Map((e.exceptions??[]).map(e=>[e.recurrenceId,e])),f=[];for(let r=l;r<=u;r=A(r,1)){if(r<i||!ve(e,r))continue;let c=_e(r,a,e.allDay),l=d.get(c),u=r,p=A(r,s);if(!e.allDay){let t=g(`${r}T${a}`,e.timezone);if(!t.value)continue;u=t.value,p=new Date(Date.parse(u)+o).toISOString()}let m=be({...e,start:u,end:p},c,l);m&&xe(m,t,n)&&f.push(m)}for(let r of e.exceptions??[]){if(!ye(r,e,t,n)||f.some(t=>t.id===`${e.id}#${r.recurrenceId}`))continue;let i=j(e,r.recurrenceId),a=i?be({...i,id:e.id},r.recurrenceId,r):null;a&&xe(a,t,n)&&f.push(a)}return f.sort((e,t)=>e.start.localeCompare(t.start))}function M(e,t,n){let r=[];for(let a of e)a.recurrence?r.push(...Se(a,t,n)):xe(a,t,n)&&r.push(a),r.length>1e4&&i(`Occurrence limit exceeded; narrow the date range.`);return r.sort((e,t)=>e.start.localeCompare(t.start))}function Ce(e){let t=e.exceptions??[];return t.length?!e.recurrence||new Set(t.map(e=>e.recurrenceId)).size!==t.length?!1:t.every(t=>j(e,t.recurrenceId)!==null):!0}function we(e){return e.replace(/<br\s*\/?>/gi,`
1
+ function e(e={}){let t=[];return new Headers(e.headers).forEach((e,n)=>t.push([n,e])),{__emdashPluginResponse:!0,status:e.status??200,headers:t,body:e.body??null}}function t(e){return e}const n=`Enter a valid IANA timezone, such as Europe/Paris.`,r=`External URL must use HTTP or HTTPS.`;function i(e){throw Error(e)}const a=e=>typeof e==`string`?e:``;function o(e,t){let n=new Date(0);return n.setUTCFullYear(e,t,0),n.getUTCDate()}function s(e){let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;let n=Number(t[1]),r=Number(t[2]),i=Number(t[3]);return r<1||r>12||i<1||i>o(n,r)?null:{year:n,month:r,day:i,hour:0,minute:0}}function c(e){let t=/^(\d{4}-\d{2}-\d{2})T(\d{2}):(\d{2})$/.exec(e),n=t?s(t[1]):null;if(!n||!t)return null;let r=Number(t[2]),i=Number(t[3]);return r>23||i>59?null:{...n,hour:r,minute:i}}const l=new Map;function u(e,t){try{let n=l.get(t);n||(n=new Intl.DateTimeFormat(`en`,{timeZone:t,calendar:`gregory`,numberingSystem:`latn`,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`}),l.size>=128&&l.delete(l.keys().next().value),l.set(t,n));let r=n.formatToParts(e),i=e=>Number(r.find(t=>t.type===e)?.value),a={year:i(`year`),month:i(`month`),day:i(`day`),hour:i(`hour`),minute:i(`minute`)};return Object.values(a).every(Number.isFinite)?a:null}catch{return null}}function d(e){let t=new Date(0);return t.setUTCFullYear(e.year,e.month-1,e.day),t.setUTCHours(e.hour,e.minute,0,0),t.getTime()}function f(e,t){return e.year===t.year&&e.month===t.month&&e.day===t.day&&e.hour===t.hour&&e.minute===t.minute}function p(e){return s(e)!==null}function m(e,t){let n=new Date(`${e}T00:00:00Z`);return n.setUTCDate(n.getUTCDate()+t),n.toISOString().slice(0,10)}function h(e){if(!e.trim())return!1;try{return new Intl.DateTimeFormat(`en`,{timeZone:e}),!0}catch{return!1}}function g(e,t){let r=c(e);if(!r)return{error:`Enter a valid date and time.`};if(!h(t))return{error:n};let i=d(r),a=new Set,o=!1;for(let e=-36;e<=36;e+=3){let n=i+e*36e5,s=u(new Date(n),t);if(!s)continue;o=!0;let c=i-(d(s)-n),l=u(new Date(c),t);l&&f(l,r)&&a.add(c)}return o?a.size?{value:new Date(Math.min(...a)).toISOString()}:{error:`That local time does not exist because of a daylight-saving change.`}:{error:`The selected timezone could not be applied.`}}function _(e,t){let n=new Date(e);if(Number.isNaN(n.getTime())||!h(t))return``;let r=u(n,t);if(!r)return``;let i=e=>String(e).padStart(2,`0`);return`${String(r.year).padStart(4,`0`)}-${i(r.month)}-${i(r.day)}T${i(r.hour)}:${i(r.minute)}`}function v(e,t,n){if(t)return p(e)?e:``;let r=new Date(e);if(Number.isNaN(r.getTime()))return``;let i=u(r,h(n)?n:`UTC`);return i?`${String(i.year).padStart(4,`0`)}-${String(i.month).padStart(2,`0`)}-${String(i.day).padStart(2,`0`)}`:``}function y(e){let t={};if(e.allDay)return p(e.start)||(t.start=`Choose a valid start date.`),p(e.end)||(t.end=`Choose a valid end date.`),!t.start&&!t.end&&e.end<e.start&&(t.end=`The end must be on or after the start.`),Object.keys(t).length?{errors:t}:{dates:{start:e.start,end:e.end},errors:t};if(!h(e.timezone))return t.timezone=n,{errors:t};let r=g(e.start,e.timezone),i=g(e.end,e.timezone);return r.value||(t.start=r.error),i.value||(t.end=i.error),r.value&&i.value&&Date.parse(i.value)<Date.parse(r.value)&&(t.end=`The end must be on or after the start.`),Object.keys(t).length?{errors:t}:{dates:{start:r.value,end:i.value},errors:t}}function b(e){let t=typeof e==`string`?e.split(/[,\r\n]+/):e,n=[],r=new Set;for(let e of t){let t=e.trim().replace(/\s+/g,` `);if(!t)continue;let i=t.toLowerCase();r.has(i)||(r.add(i),n.push(t))}return n}function x(e){return e.trim().replace(/\s+/g,` `).toLowerCase()}function ee(e){return e==null||e===``?[]:(typeof e==`string`&&e.trim().startsWith(`[`)&&(e=JSON.parse(e)),typeof e==`string`||(!Array.isArray(e)||e.some(e=>typeof e!=`string`))&&i(`Categories must be comma-separated text or an array of names.`),b(e))}function S(e){return[e.street,e.street2,e.locality,e.region,e.postalCode,e.country].map(e=>e?.trim()).filter(Boolean).join(`, `)}function C(e,t){return[e?.name,e?S(e):``,t.trim()].filter(Boolean).join(` · `)}function w(e){let t=e.trim();if(!t)return``;let n=`https://www.google.com/maps/dir/?api=1&destination=${encodeURIComponent(t)}`;return n.length<=2048?n:``}function T(e){if(typeof e!=`string`||!e.trim())return``;try{let t=new URL(e);return t.hostname&&(t.protocol===`http:`||t.protocol===`https:`)?t.href:``}catch{return``}}const E=[`sunday`,`monday`,`tuesday`,`wednesday`,`thursday`,`friday`,`saturday`];function D(e){if(!e||typeof e!=`object`)return!1;let t=e;if(typeof t.until!=`string`||!p(t.until)||t.interval!==void 0&&(typeof t.interval!=`number`||!Number.isInteger(t.interval)||t.interval<1||t.interval>52))return!1;if(t.frequency===`daily`)return t.weekdays===void 0;if(t.frequency===`weekly`)return t.weekdays===void 0||Array.isArray(t.weekdays)&&t.weekdays.length>=1&&t.weekdays.length<=7&&new Set(t.weekdays).size===t.weekdays.length&&t.weekdays.every(e=>E.includes(e));if(t.frequency!==`monthly`||!t.pattern||typeof t.pattern!=`object`)return!1;let n=t.pattern;return n.type===`dayOfMonth`?Number.isInteger(n.dayOfMonth)&&Number(n.dayOfMonth)>=1&&Number(n.dayOfMonth)<=31&&(n.missingDayBehavior===`skip`||n.missingDayBehavior===`lastDay`):n.type===`weekdayOfMonth`&&E.includes(n.weekday)&&(n.position===`last`||Number.isInteger(n.position)&&Number(n.position)>=1&&Number(n.position)<=5)}function te(e){let t=e.interval??1;return e.frequency===`weekly`&&e.weekdays?`every ${t===1?`week`:`${t} weeks`} on ${e.weekdays.map(e=>e[0].toUpperCase()+e.slice(1)).join(`, `)}`:t===1?e.frequency:`every ${t} ${e.frequency===`daily`?`days`:e.frequency===`weekly`?`weeks`:`months`}`}function ne(e){return[...e].sort((e,t)=>(E.indexOf(e)+6)%7-(E.indexOf(t)+6)%7)}const re=[`sunday`,`monday`,`tuesday`,`wednesday`,`thursday`,`friday`,`saturday`];function ie(e){return e.slice(0,10).split(`-`).map(Number)}function ae(e){let[t,n,r]=ie(e);return re[new Date(Date.UTC(t,n-1,r)).getUTCDay()]}function oe(e){let[,,t]=ie(e);return Math.ceil(t/7)}function se(e){let[t,n,r]=ie(e),i=new Date(Date.UTC(t,n-1,r+7));return i.getUTCMonth()!==n-1||i.getUTCFullYear()!==t}function ce(e){if(e.repeatFrequency===`none`)return;let t={until:e.recurrenceUntil,...e.recurrenceInterval!==void 0&&e.recurrenceInterval!==1?{interval:e.recurrenceInterval}:{}};return e.repeatFrequency===`daily`||e.repeatFrequency===`weekly`?{frequency:e.repeatFrequency,...t,...e.repeatFrequency===`weekly`&&e.weeklyWeekdays?.length?{weekdays:ne(e.weeklyWeekdays)}:{}}:{frequency:`monthly`,...t,pattern:e.monthlyPattern===`dayOfMonth`?{type:`dayOfMonth`,dayOfMonth:e.monthlyDayOfMonth??Number(e.start.slice(8,10)),missingDayBehavior:e.missingDayBehavior}:{type:`weekdayOfMonth`,weekday:e.monthlyWeekday,position:e.monthlyPosition}}}function le(e,t){return e?!t||t===`draft`?`published`:t:`draft`}function ue(e,t){let n=e.title.trim();if(!n)return{error:`Event title is required.`};if(e.externalUrl.trim()&&!T(e.externalUrl))return{error:r};if(e.virtualUrl?.trim()&&!T(e.virtualUrl))return{error:`Virtual URL must use HTTP or HTTPS.`};if(e.imageUrl.trim()&&!T(e.imageUrl))return{error:`Image URL must use HTTP or HTTPS.`};let i=t?{dates:t,errors:{}}:y({start:e.start,end:e.end,allDay:e.allDay,timezone:e.timezone});if(!i.dates)return{error:i.errors.start??i.errors.end??i.errors.timezone??`Check the event dates.`};let a=e.start.slice(0,10),o=ce(e);if(o&&!D(o))return{error:`Choose a valid repeat pattern and an integer interval from 1 through 52.`};if(o?.frequency===`weekly`&&o.weekdays&&!o.weekdays.includes(ae(a)))return{error:`The first event must fall on one of the selected weekly days.`};if(o&&(!p(o.until)||o.until<a))return{error:`Choose a recurrence end date on or after the first event.`};if(o?.frequency===`monthly`&&o.pattern.type===`weekdayOfMonth`&&(ae(a)!==o.pattern.weekday||(o.pattern.position===`last`?!se(a):oe(a)!==o.pattern.position)))return{error:`The first event must match the selected monthly weekday pattern.`};if(o?.frequency===`monthly`&&o.pattern.type===`dayOfMonth`){let[e,t,n]=ie(a),r=new Date(Date.UTC(e,t,0)).getUTCDate();if(n!==(o.pattern.missingDayBehavior===`lastDay`?Math.min(o.pattern.dayOfMonth,r):o.pattern.dayOfMonth))return{error:`The first event must match the selected monthly day and missing-day policy.`}}let s=b(e.categories),c=(e.featuredMediaId||e.imageMediaId||``).trim();return{data:{title:n,description:e.description.trim(),...i.dates,allDay:e.allDay,timezone:e.timezone.trim(),location:e.location.trim(),locationType:e.locationType??`physical`,...e.virtualUrl?.trim()?{virtualUrl:T(e.virtualUrl)}:{},status:le(e.published,e.status),organizer:e.organizer.trim(),...e.organizerId?{organizerId:e.organizerId}:{},externalUrl:T(e.externalUrl),imageUrl:c?``:T(e.imageUrl),...c?{imageMediaId:c,featuredMediaId:c}:{},categories:s,...e.venueId?{venueId:e.venueId}:{},published:e.published,...o?{recurrence:o}:{},exceptions:e.exceptions}}}function de(e){let t=e.timezone||`UTC`,n=e.allDay?e.start.slice(0,10):_(e.start,t),r=e.allDay?e.end.slice(0,10):_(e.end,t),i=e.recurrence;return{title:e.title,description:e.description,start:n,end:r,allDay:e.allDay,timezone:t,location:e.location,locationType:e.locationType??`physical`,virtualUrl:e.virtualUrl??``,status:le(e.published,e.status),organizer:e.organizer,organizerId:e.organizerId,externalUrl:e.externalUrl,imageUrl:e.imageUrl,imageMediaId:e.featuredMediaId??e.imageMediaId??``,featuredMediaId:e.featuredMediaId??e.imageMediaId??void 0,categories:e.categories.join(`, `),venueId:e.venueId??``,published:e.published,repeatFrequency:i?.frequency??`none`,recurrenceUntil:i?.until??``,recurrenceInterval:i?.interval??1,weeklyWeekdays:i?.frequency===`weekly`?i.weekdays:void 0,monthlyDayOfMonth:i?.frequency===`monthly`&&i.pattern.type===`dayOfMonth`?i.pattern.dayOfMonth:Number(n.slice(8,10)),monthlyPattern:i?.frequency===`monthly`?i.pattern.type:`dayOfMonth`,missingDayBehavior:i?.frequency===`monthly`&&i.pattern.type===`dayOfMonth`?i.pattern.missingDayBehavior:`skip`,monthlyWeekday:i?.frequency===`monthly`&&i.pattern.type===`weekdayOfMonth`?i.pattern.weekday:ae(n),monthlyPosition:i?.frequency===`monthly`&&i.pattern.type===`weekdayOfMonth`?i.pattern.position:n?oe(n):1,exceptions:e.exceptions??[]}}const fe=[`sunday`,`monday`,`tuesday`,`wednesday`,`thursday`,`friday`,`saturday`];function O(e){let[t,n,r]=e.split(`-`).map(Number);return new Date(Date.UTC(t,n-1,r))}function pe(e){return`${String(e.getUTCFullYear()).padStart(4,`0`)}-${String(e.getUTCMonth()+1).padStart(2,`0`)}-${String(e.getUTCDate()).padStart(2,`0`)}`}function k(e,t){let n=O(e);return n.setUTCDate(n.getUTCDate()+t),pe(n)}function me(e,t){return(O(t).getTime()-O(e).getTime())/864e5}function he(e){let t=O(e);return Math.ceil(t.getUTCDate()/7)}function ge(e,t){if(t.frequency!==`monthly`)return!1;let n=O(e);if(t.pattern.type===`dayOfMonth`){let e=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth()+1,0)).getUTCDate(),r=t.pattern.missingDayBehavior===`lastDay`?Math.min(t.pattern.dayOfMonth,e):t.pattern.dayOfMonth;return n.getUTCDate()===r}if(fe[n.getUTCDay()]!==t.pattern.weekday)return!1;if(t.pattern.position!==`last`)return he(e)===t.pattern.position;let r=O(k(e,7));return r.getUTCMonth()!==n.getUTCMonth()||r.getUTCFullYear()!==n.getUTCFullYear()}function _e(e){return e.allDay?e.start.slice(0,10):_(e.start,e.timezone).slice(0,10)}function ve(e,t,n){return n?e:`${e}T${t}`}function ye(e,t){let n=e.recurrence,r=_e(e);if(!n||t<r||t>n.until)return!1;let i=n.interval??1,a=me(r,t);if(n.frequency===`daily`)return a%i===0;if(n.frequency===`weekly`){let e=Math.floor((a+(O(r).getUTCDay()+6)%7)/7),o=O(t).getUTCDay();return e%i===0&&(n.weekdays?n.weekdays.includes(fe[o]):o===O(r).getUTCDay())}let o=O(t),s=O(r);return((o.getUTCFullYear()-s.getUTCFullYear())*12+o.getUTCMonth()-s.getUTCMonth())%i===0&&ge(t,n)}function A(e,t){let n=t.slice(0,10);if(!p(n)||!ye(e,n))return null;let r=e.allDay?``:_(e.start,e.timezone).slice(11,16);if(t!==ve(n,r,e.allDay))return null;let i=n,a=k(n,me(e.start.slice(0,10),e.end.slice(0,10)));if(!e.allDay){let t=g(`${n}T${r}`,e.timezone);if(!t.value)return null;i=t.value,a=new Date(Date.parse(i)+Date.parse(e.end)-Date.parse(e.start)).toISOString()}return xe({...e,start:i,end:a},t)}function be(e,t,n,r){if(e.status!==`modified`||!e.overrides?.start)return!1;let i=e.overrides.start,a=e.overrides.allDay??t.allDay,o=e.overrides.timezone??t.timezone,s=a?i.slice(0,10):v(i,!1,o),c=e.overrides.end??i,l=a?c.slice(0,10):v(c,!1,o);return s<=r&&l>=n}function xe(e,t,n){if(n?.status===`cancelled`)return null;let{recurrence:r,exceptions:i,previousStartDate:a,scheduleHistory:o,...s}=e;return{...s,...n?.overrides,...n?.overrides?.start&&n.overrides.start!==e.start?{previousStartDate:e.start}:{},...n?.overrides?.organizer===void 0?{}:{organizerId:void 0,organizerDetails:void 0},...n?.overrides?.description===void 0?{}:{descriptionBlocks:(()=>{let e=n.overrides.description;if(Array.isArray(e))return e;try{let t=JSON.parse(String(e));return Array.isArray(t)?t:void 0}catch{return}})(),description:typeof n.overrides.description==`string`?n.overrides.description:JSON.stringify(n.overrides.description)},status:le(e.published,n?.overrides?.status??e.status),id:`${e.id}#${t}`,exceptions:[],createdAt:e.createdAt,updatedAt:e.updatedAt}}function Se(e,t,n){let r=v(e.start,e.allDay,e.timezone),i=v(e.end,e.allDay,e.timezone);return r<=n&&i>=t}function Ce(e,t,n){let r=e.recurrence;if(!r||!p(t)||!p(n)||t>n||me(t,n)>=366)return[];let i=_e(e);if(!p(i)||i>r.until)return[];let a=e.allDay?``:_(e.start,e.timezone).slice(11,16),o=Date.parse(e.end)-Date.parse(e.start),s=e.allDay?me(e.start.slice(0,10),e.end.slice(0,10)):0,c=e.allDay?s:Math.ceil(o/864e5),l=k(t,-Math.min(366,c)),u=n<r.until?n:r.until,d=new Map((e.exceptions??[]).map(e=>[e.recurrenceId,e])),f=[];for(let r=l;r<=u;r=k(r,1)){if(r<i||!ye(e,r))continue;let c=ve(r,a,e.allDay),l=d.get(c),u=r,p=k(r,s);if(!e.allDay){let t=g(`${r}T${a}`,e.timezone);if(!t.value)continue;u=t.value,p=new Date(Date.parse(u)+o).toISOString()}let m=xe({...e,start:u,end:p},c,l);m&&Se(m,t,n)&&f.push(m)}for(let r of e.exceptions??[]){if(!be(r,e,t,n)||f.some(t=>t.id===`${e.id}#${r.recurrenceId}`))continue;let i=A(e,r.recurrenceId),a=i?xe({...i,id:e.id},r.recurrenceId,r):null;a&&Se(a,t,n)&&f.push(a)}return f.sort((e,t)=>e.start.localeCompare(t.start))}function j(e,t,n){let r=[];for(let a of e)a.recurrence?r.push(...Ce(a,t,n)):Se(a,t,n)&&r.push(a),r.length>1e4&&i(`Occurrence limit exceeded; narrow the date range.`);return r.sort((e,t)=>e.start.localeCompare(t.start))}function we(e){let t=e.exceptions??[];return t.length?!e.recurrence||new Set(t.map(e=>e.recurrenceId)).size!==t.length?!1:t.every(t=>A(e,t.recurrenceId)!==null):!0}function Te(e){return e.replace(/<br\s*\/?>/gi,`
2
2
  `).replace(/<\/p>/gi,`
3
3
 
4
- `).replace(/<\/?(?:p|div|span|a|b|strong|em|i|ul|ol|li|h[1-6]|blockquote)(?:\s[^>]*)?>/gi,``).replace(/&amp;/g,`&`).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&quot;/g,`"`).replace(/&#39;/g,`'`).trim()}function N(e){if(typeof e==`string`){let t=e.trim();if(t.startsWith(`[`))try{let e=JSON.parse(t);if(Array.isArray(e))return N(e)}catch{}return N(Te(t))}if(!Array.isArray(e))return``;let t=[];for(let n of e){if(!n||typeof n!=`object`)continue;let e=n;if(e._type&&e._type!==`block`)continue;let r=new Map;for(let t of Array.isArray(e.markDefs)?e.markDefs:[])t&&typeof t._key==`string`&&typeof t.href==`string`&&/^(?:https?:|mailto:)/i.test(t.href)&&r.set(t._key,t.href);let i=(Array.isArray(e.children)?e.children:[]).map(e=>{if(!e||typeof e.text!=`string`)return``;let t=(Array.isArray(e.marks)?e.marks:[]).map(e=>r.get(e)).find(Boolean);return e.text+(t&&!e.text.includes(t)?` (`+t+`)`:``)}).join(``).trim();i&&t.push((e.listItem===`bullet`?`- `:e.listItem===`number`?`1. `:``)+i)}return t.join(`
4
+ `).replace(/<\/?(?:p|div|span|a|b|strong|em|i|ul|ol|li|h[1-6]|blockquote)(?:\s[^>]*)?>/gi,``).replace(/&amp;/g,`&`).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&quot;/g,`"`).replace(/&#39;/g,`'`).trim()}function M(e){if(typeof e==`string`){let t=e.trim();if(t.startsWith(`[`))try{let e=JSON.parse(t);if(Array.isArray(e))return M(e)}catch{}return M(Ee(t))}if(!Array.isArray(e))return``;let t=[];for(let n of e){if(!n||typeof n!=`object`)continue;let e=n;if(e._type&&e._type!==`block`)continue;let r=new Map;for(let t of Array.isArray(e.markDefs)?e.markDefs:[])t&&typeof t._key==`string`&&typeof t.href==`string`&&/^(?:https?:|mailto:)/i.test(t.href)&&r.set(t._key,t.href);let i=(Array.isArray(e.children)?e.children:[]).map(e=>{if(!e||typeof e.text!=`string`)return``;let t=(Array.isArray(e.marks)?e.marks:[]).map(e=>r.get(e)).find(Boolean);return e.text+(t&&!e.text.includes(t)?` (`+t+`)`:``)}).join(``).trim();i&&t.push((e.listItem===`bullet`?`- `:e.listItem===`number`?`1. `:``)+i)}return t.join(`
5
5
 
6
- `)}function Te(e){if(typeof e!=`string`||!e.trim())return[];let t=[],n=[],r=(e,n=`normal`,r,i)=>{let a=`block_`+t.length,o=[],s=[],c=/\[([^\]]+)\]\((https?:\/\/[^\s)]+|mailto:[^\s)]+)\)|\*\*([^*]+)\*\*|__([^_]+)__|\*([^*]+)\*|_([^_]+)_|\x60([^\x60]+)\x60/g,l=0,u,d=(e,t=[])=>{e&&s.push({_type:`span`,_key:a+`_`+s.length,text:e,marks:t})};for(;u=c.exec(e);){if(d(e.slice(l,u.index)),u[1]&&u[2]){let e=a+`_link_`+o.length;o.push({_key:e,_type:`link`,href:u[2]}),d(u[1],[e])}else d(u[3]??u[4]??u[5]??u[6]??u[7]??``,[u[3]||u[4]?`strong`:u[7]?`code`:`em`]);l=u.index+u[0].length}d(e.slice(l)),t.push({_type:`block`,_key:a,style:n,markDefs:o,children:s,...r?{listItem:r,level:i??1}:{}})},i=()=>{n.length&&r(n.join(`
6
+ `)}function Ee(e){if(typeof e!=`string`||!e.trim())return[];let t=[],n=[],r=(e,n=`normal`,r,i)=>{let a=`block_`+t.length,o=[],s=[],c=/\[([^\]]+)\]\((https?:\/\/[^\s)]+|mailto:[^\s)]+)\)|\*\*([^*]+)\*\*|__([^_]+)__|\*([^*]+)\*|_([^_]+)_|\x60([^\x60]+)\x60/g,l=0,u,d=(e,t=[])=>{e&&s.push({_type:`span`,_key:a+`_`+s.length,text:e,marks:t})};for(;u=c.exec(e);){if(d(e.slice(l,u.index)),u[1]&&u[2]){let e=a+`_link_`+o.length;o.push({_key:e,_type:`link`,href:u[2]}),d(u[1],[e])}else d(u[3]??u[4]??u[5]??u[6]??u[7]??``,[u[3]||u[4]?`strong`:u[7]?`code`:`em`]);l=u.index+u[0].length}d(e.slice(l)),t.push({_type:`block`,_key:a,style:n,markDefs:o,children:s,...r?{listItem:r,level:i??1}:{}})},i=()=>{n.length&&r(n.join(`
7
7
  `)),n=[]},a=!1;for(let t of e.replace(/\r\n?/g,`
8
8
  `).split(`
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=``,n=`eventual`){let r=e.title||`Event`,i=E(e.virtualUrl??``),a=[e.description||``,i].filter(Boolean).join(`
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(Te(t))}return i(),t}function De(e,t){return t.venueId?e?.get(t.venueId+`|`+(t.locale??``).toLowerCase())??e?.get(t.venueId):void 0}function Oe(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=M(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 ke(e,t=``,n=`eventual`){let r=e.title||`Event`,i=T(e.virtualUrl??``),a=[M(e.description??``),i].filter(Boolean).join(`
10
10
 
11
- `),o=e.location||``;e.locationType===`virtual`?o=i||o:e.locationType===`hybrid`&&i&&o&&(o=`${o} · ${i}`);let s,c,l,u=``;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),s=`${t}/${n.toISOString().slice(0,10).replace(/-/g,``)}`,c=e.start.slice(0,10),l=n.toISOString().slice(0,10),u=`&allday=true`}else{let t=new Date(e.start).toISOString(),n=new Date(e.end).toISOString();s=`${t.replace(/[-:]/g,``).replace(/\.\d{3}/,``)}/${n.replace(/[-:]/g,``).replace(/\.\d{3}/,``)}`,c=t,l=n}let d=encodeURIComponent,f=`https://calendar.google.com/calendar/render?action=TEMPLATE&text=${d(r)}&dates=${s}&details=${d(a)}&location=${d(o)}`,p=`path=/calendar/action/compose&rru=addevent&subject=${d(r)}&body=${d(a)}&location=${d(o)}&startdt=${d(c)}&enddt=${d(l)}${u}`,m=`https://outlook.live.com/calendar/0/deeplink/compose?${p}`,h=`https://outlook.office.com/calendar/0/deeplink/compose?${p}`,g=e.id.split(`#`)[0],_=`/_emdash/api/plugins/${d(n)}/calendar?eventId=${d(g)}`;return{google:f,outlook:m,office365:h,ics:t?new URL(_,t).href:_}}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},``,n)}}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),c=`/_emdash/api/plugins/`+encodeURIComponent(t.plugin?.id||`eventual`)+`/`;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 l=[{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 c=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({...c,title:String(c.title??`Event`)+` (copy)`}).filter(([e])=>u.has(e))),{locale:e.locale??void 0});l.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 u=await F(t);l.push({type:`actions`,elements:[o(s+`/new`,`Create event`),o(s,`All events`),...[`venue`,`organizer_ref`].flatMap(e=>{let t=I(a,e);return u.some(e=>e.slug===t)?[o(`/_emdash/admin/content/`+encodeURIComponent(t),e===`venue`?`Manage venues`:`Manage organizers`)]:[]})]});let d=String(r.action_id).startsWith(`page-native-events`)?String(r.value||``):void 0,f=await t.content.list(a.slug,{limit:20,cursor:d});l.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:f.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.`}),f.hasMore&&(!f.cursor||f.cursor===d)&&i(`Incomplete event page. Reload the workspace.`);let p=[...d?[{type:`button`,action_id:`page-native-events-first`,label:`First page`,value:``}]:[],...f.hasMore?[{type:`button`,action_id:`page-native-events-next`,label:`Next events`,value:f.cursor}]:[]];return p.length&&l.push({type:`actions`,elements:p}),l.push({type:`header`,text:`Subscribe`},{type:`actions`,elements:[o(c+`calendar`,`Calendar subscription (.ics)`),o(c+`publicEvents`,`Published events (JSON)`)]}),{blocks:l}}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
- `;)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,r={})=>e({status:t,headers:{"content-type":`text/plain; charset=utf-8`,"cache-control":`no-store`,...r},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
- `)}\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=n?.eventId,d=u?.split(`#`)[0],f=M(Ft(d?l.events.filter(e=>e.id===d):l.events,n?.locale,n?.strict),r,o),p=u?.includes(`#`)?f.filter(e=>e.id===u):f;p.length>1e4&&i(`Too many calendar occurrences.`);let m=n?.category?x(n.category):``,h=m?p.filter(e=>e.categories.some(e=>x(e)===m)):p;if(u&&!h.length)return``;let g=`venues`in l&&l.venues||await Nt(e,h,c.schema),_=(c.native?await It(e,h):h).map(e=>({...e,location:Ue(e,g).location})),v=!u&&e.storage?.calendar_cancellations?await xt(e):[];return er(_,u?[]:[...l.cancellations,...v].filter(e=>Date.parse(e.cancelledAt)>Date.now()-366*864e5&&(!m||e.categories?.some(e=>x(e)===m))&&(!e.feedCategory||e.feedCategory===m)&&(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=e=>Zn(503,e.message,{"retry-after":`60`});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 Zn(400,`Invalid locale.`)}let a=r.searchParams.get(`strict`)===`true`,o=r.searchParams.get(`category`)||void 0,s=r.searchParams.get(`eventId`)?.trim()||void 0,c=await gr(n,r.host||`localhost`,{locale:i,strict:a,category:o,eventId:s});return c?e({status:200,headers:{"content-type":`text/calendar; charset=utf-8`},body:{kind:`text`,value:c}}):Zn(404,`This event has ended or is no longer published.`)}catch(e){return xi(e instanceof ft||e instanceof at?e:Error(`Calendar feed unavailable; retry later.`))}}})}};export{Ci as default};
11
+ `),o=e.location||``;e.locationType===`virtual`?o=i||o:e.locationType===`hybrid`&&i&&o&&(o=`${o} · ${i}`);let s,c,l,u=``;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),s=`${t}/${n.toISOString().slice(0,10).replace(/-/g,``)}`,c=e.start.slice(0,10),l=n.toISOString().slice(0,10),u=`&allday=true`}else{let t=new Date(e.start).toISOString(),n=new Date(e.end).toISOString();s=`${t.replace(/[-:]/g,``).replace(/\.\d{3}/,``)}/${n.replace(/[-:]/g,``).replace(/\.\d{3}/,``)}`,c=t,l=n}let d=encodeURIComponent,f=`https://calendar.google.com/calendar/render?action=TEMPLATE&text=${d(r)}&dates=${s}&details=${d(a)}&location=${d(o)}`,p=`path=/calendar/action/compose&rru=addevent&subject=${d(r)}&body=${d(a)}&location=${d(o)}&startdt=${d(c)}&enddt=${d(l)}${u}`,m=`https://outlook.live.com/calendar/0/deeplink/compose?${p}`,h=`https://outlook.office.com/calendar/0/deeplink/compose?${p}`,g=e.id.split(`#`)[0],_=`/_emdash/api/plugins/${d(n)}/calendar?eventId=${d(g)}`;return{google:f,outlook:m,office365:h,ics:t?new URL(_,t).href:_}}function Ae(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 je(e){let t=Ae(e.virtualUrl??``);return e.locationType===`virtual`?t||e.location:e.locationType===`hybrid`?[e.location,t].filter(Boolean).join(` · `):e.location}function Me(e){return Ae(e.externalUrl)||(e.locationType===`virtual`||e.locationType===`hybrid`?Ae(e.virtualUrl??``):``)}function Ne(e){return e.status===`cancelled`?`CANCELLED`:e.status===`postponed`?`TENTATIVE`:`CONFIRMED`}function Pe(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 N(e){if(typeof e!=`string`)return e??void 0;if(e.trim())try{return JSON.parse(e)}catch{i(`Invalid JSON.`)}}const Fe=[`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 Ie(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)&&!Pe(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(Pe(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=N(e.recurrence);if(d!=null&&!D(d)&&i(`Invalid recurrence rule.`),d&&D(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=N(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=A(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=>!Pe(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]&&!Ae(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||!we(g))&&i(`Duplicate or invalid exception recurrence IDs.`);let v=N(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||!A(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`||!Ae(e[t]))&&i(`Public URLs must use HTTP(S): `+t);let b=N(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&&!Ae(t)}))&&i(`Invalid organizer details.`),e.previous_start_date&&!p(e.previous_start_date)&&!Pe(e.previous_start_date)&&i(`Invalid previous start date.`);let x=N(e.schedule_history);return x!=null&&(!Array.isArray(x)||x.length>10||x.some(e=>!e||!Pe(e.changedAt)||!h(e.timezone)||typeof e.allDay!=`boolean`||(e.allDay?!p(e.start)||!p(e.end)||e.end<e.start:!Pe(e.start)||!Pe(e.end)||Date.parse(e.end)<Date.parse(e.start))))&&i(`Invalid schedule history.`),n.all_day=a,n.timezone=o,ee(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 Le=new Set([`image/avif`,`image/gif`,`image/jpeg`,`image/png`,`image/webp`]),Re=8*1024*1024;function ze(e){return Le.has(e.toLowerCase())}function Be(e,t){let n=new URLSearchParams({eventId:t});return`/_emdash/api/plugins/${encodeURIComponent(e)}/publicEventImage?${n}`}function Ve(e,t,n=`eventual`,r){let i=C(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`,...T(e.virtualUrl??``)?{virtualUrl:T(e.virtualUrl??``)}:{},status:le(e.published,e.status),organizer:r?.name??(e.organizer||e.organizerDetails?.name||``),...r?{organizerDetails:{id:r.id,name:r.name,website:T(r.website),contactUrl:T(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:Be(n,e.id):e.imageUrl||``,...e.imageMedia?{imageMedia:e.imageMedia}:{},categories:b(e.categories),venue:t?{id:t.id,name:t.name,address:S(t),addressParts:{street:t.street,street2:t.street2,locality:t.locality,region:t.region,postalCode:t.postalCode,country:t.country}}:null,directionsUrl:w(i),calendarLinks:ke({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},``,n)}}const He=e=>e instanceof Date?e.toISOString():a(e);function Ue(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=N(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=Ie({...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=N(r.recurrence),p=e.map(e=>({...e,overrides:e.overrides?{...e.overrides}:void 0})),m=N(r.occurrence_content)??[];for(let e of m){if(!f||!A({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`?N(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=ee(r.categories),S=a(v?.id??r.featuredMediaId??r.featured_media_id??r.imageMediaId),C=v?.meta?.storageKey,w=a(v?.src||v?.url)||(C?`/_emdash/api/media/file/`+encodeURIComponent(String(C)):``),T=e=>typeof e==`number`&&e>0?e:void 0,E=w?{src:w,width:T(v?.width),height:T(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:N(r.organizer_details),venueId:b,imageUrl:S?``:a(r.image_url??r.imageUrl??v?.src??v?.url),imageMediaId:S,featuredMediaId:S||void 0,imageMedia:E,categories:x,createdAt:He(t.createdAt??r.created_at??r.createdAt)||`1970-01-01T00:00:00.000Z`,updatedAt:He(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:N(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 We(e,t,n,r=`eventual`){let i=De(t,e),a=Ve(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:M(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 Ge=new WeakMap;function Ke(e,t,n){let r=Ge.get(e);return r||Ge.set(e,r=Object.create(null)),r[t]??=Promise.resolve().then(n)}function qe(e,t){let n=Ge.get(e);n&&delete n[t]}const Je=`collections`,Ye=`legacyReads`,Xe=/^[a-z][a-z0-9_]{0,62}$/;async function Ze(e){return(await Qe(e))?.events??`events`}function Qe(e){return Ke(e,`collection-settings`,async()=>await e.settings?.get(Je)??void 0)}function $e(e){return Ke(e,`legacy-reads`,async()=>await e.settings?.get(Ye)===!0)}async function et(e,t){await e.settings.set(Ye,t),qe(e,`legacy-reads`)}function P(e){return Ke(e,`schemas`,async()=>await e.schema?.listCollections()??[])}function tt(e){return Ke(e,`bindings`,()=>nt(e))}async function nt(e){let[t,n]=await Promise.all([Qe(e),P(e)]);t&&(!t.events||Object.values(t).some(e=>typeof e!=`string`||e!==``&&!Xe.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 rt(e,t){(!t.events||Object.values(t).some(e=>typeof e!=`string`||e!==``&&!Xe.test(e)))&&i(`Choose valid collection names.`);let n=await P(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(Je,t),qe(e,`collection-settings`),qe(e,`bindings`)}function it(e){if(typeof e==`string`)return e.trim()||void 0;if(e&&typeof e==`object`&&!Array.isArray(e))return it(e.id)}function F(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 at(e,t){return(e?.fields.find(e=>e.slug===t))?.validation?.relation?t===`venue`?`venue_id`:`organizer_id`:t}async function I(e){return(await tt(e)).schema}var ot=class extends Error{constructor(){super(`The sandbox RPC budget is exceeded.`),this.name=`SandboxBudgetError`}};const st=Symbol(`eventual invocation budget`),ct=new WeakMap;function L(e,t=10){if(e[st])return e;let n=ct.get(e);if(n)return n;let r={used:0,reserved:0,limit:t},i={...e,[st]:r},a=e=>new Proxy(e,{get(e,t){let n=Reflect.get(e,t,e);return typeof n==`function`?(...t)=>{if(r.used+r.reserved>=r.limit)throw new ot;return r.used++,Reflect.apply(n,e,t)}:n}});for(let[t,n]of Object.entries(e))![`site`,`plugin`,`storage`].includes(t)&&n&&typeof n==`object`&&(i[t]=a(n));return e.storage&&(i.storage=new Proxy(e.storage,{get(e,t){let n=Reflect.get(e,t,e);return n&&typeof n==`object`?a(n):n}})),ct.set(e,i),i}function lt(e,t){let n=e[st];if(!n)return()=>{};if(n.used+n.reserved+t>n.limit)throw new ot;n.reserved+=t;let r=!1;return()=>{r||=(n.reserved-=t,!0)}}function ut(e){let t=e[st];return t?t.limit-t.used-t.reserved:10}function dt(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 ft=1e4;var pt=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 mt(e){return e.storage.events}function ht(e){return e.storage.venues}function gt(e){return e.storage.calendar_cancellations}function R(e,t){return mt(e).get(t)}function _t(e,t){return yt(e,t)}function vt(e){return new Date(Math.max(Date.now(),Date.parse(e??``)+1||0)).toISOString()}async function yt(e,t){let n=await mt(e).get(t.id);t=dt(n,t);let r=await xt(e,n,t);await mt(e).put(t.id,t);for(let t=0;t<r.length;t+=100)await gt(e).deleteMany(r.slice(t,t+100));return t}async function bt(e,t){return await xt(e,await mt(e).get(t),null),mt(e).delete(t)}async function xt(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?j([t],r,a):[],s=n?.published?j([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 gt(e).putMany(h),u}async function St(e){let t=[],n;do{let r=await gt(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>ft)throw new pt(ft);n=r.hasMore?r.cursor:void 0}while(n);return t}function Ct(e,t){return ht(e).get(t)}function wt(e,t){return ht(e).put(t.id,t)}function Tt(e,t){return ht(e).delete(t)}async function Et(e,t){return await mt(e).count({venueId:t})>0}async function Dt(e,t={}){let n=[],r=t.maxItems??ft;if(!Number.isInteger(r)||r<1||r>ft)throw RangeError(`maxItems must be between 1 and ${ft}`);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 mt(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 pt(r)}while(a);return n}async function Ot(e){let t=[],n;do{let r=await ht(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 pt(5e3);n=r.hasMore?r.cursor:void 0}while(n);return t}async function kt(e,t){return t.length?ht(e).getMany([...new Set(t)]):new Map}function At(e){return e.storage.organizers}async function jt(e){let t=[],n;do{let r=await At(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 Mt(e,t){return t.length?At(e).getMany([...new Set(t)]):Promise.resolve(new Map)}async function z(e){if(!e.schema||!e.content)return;let t=await I(e);return t&&!t.fields?.some(e=>e.slug===`start`)&&i(`Not an event schema.`),t}async function B(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>ft)throw new pt(ft);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 Nt(e,t){let n=await z(e);if(!n)return await $e(e)||i(`Events are not connected to a content type. Turn on "Show old events saved inside the plugin".`),{native:!1,events:(await Dt(e,{published:!0,...t?{through:t}:{}})).map(t=>t.locale?t:{...t,locale:e.site?.locale??`en`}),schema:n};let r=await B(e,n.slug,!0),a=[];for(let e of r){let t=Ue(e);t||i(`Invalid event: `+e.id),t.published&&a.push(t)}return{native:!0,events:a,schema:n}}async function Pt(e,t,n){let r=new Map,i=[...new Set(t.flatMap(e=>e.venueId?[e.venueId]:[]))],a=n?await Ft(e,F(n,`venue`),t,e=>e.venueId):await kt(e,i);for(let[e,t]of a){let n=Oe(t);n&&r.set(e,n)}return r}async function Ft(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 Ke(e,`directory:`+t,()=>B(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 It(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 Lt(e,t,n=!0){let r=new Map,i=await I(e);if(t.some(e=>e.organizerId)){let n=F(i,`organizer_ref`);for(let[i,a]of await Ft(e,n,t,e=>e.organizerId))r.set(i,{id:a.id,name:String(a.data.name??a.data.title??``),website:T(String(a.data.website??``)),contactUrl:T(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(ut(e)<3)continue;let c=await Ke(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?Be(a,e.id):e.imageUrl||``}}))}function Rt(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=>!E.includes(e)))return t(`Choose valid weekdays.`);n.length&&(a.weekdays=ne(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(!E.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)?D(a)?{rule:a}:t(`Invalid `+n+` recurrence.`):t(`Unsupported recurrence frequency: `+n)}function zt(e){if(e=N(e),!D(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 Bt(e){if(e=N(e),!D(e))return`Does not repeat`;let t=te(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 Vt(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 Ht(e,t,n){return{version:1,dependencies:[...new Set([e.slug,F(e,`venue`),F(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 Ut(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function Wt(e,t){try{return await Gt(e,L(t,30))}catch(e){if(e instanceof ot)return{ok:!1,error:`SANDBOX_BUDGET_EXCEEDED`,details:e.message,events:void 0};throw e}}async function Gt(e,t){let n={ok:!1,error:`INVALID_QUERY`};if(!Ut(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 Nt(t,s),c=It(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 pt)return{ok:!1,error:`EVENT_LIMIT_EXCEEDED`,maxEvents:e.limit};throw e}let u=j(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([Pt(t,f,l.schema),Lt(t,f,[void 0,!0,`true`].includes(e.publicUrls))]);return{ok:!0,from:o,through:s,cache:Ht(l.schema,i,e.from===void 0),events:r.map(e=>We(e,n,t.site.url,t.plugin.id))}}let[h,g]=await Promise.all([kt(t,f.flatMap(e=>e.venueId?[e.venueId]:[])),Mt(t,f.flatMap(e=>e.organizerId?[e.organizerId]:[]))]);return{ok:!0,from:o,through:s,events:f.map(e=>Ve(e,e.venueId?h.get(e.venueId):void 0,t.plugin.id,e.organizerId?g.get(e.organizerId):void 0))}}async function Kt(e,t,n){let r=e,a=await z(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=(e,t)=>({type:`link`,label:t,target:{kind:`content`,collection:a.slug,id:e}}),c=`/_emdash/admin/content/`+encodeURIComponent(a.slug),l=`/_emdash/api/plugins/`+encodeURIComponent(t.plugin?.id||`eventual`)+`/`;if(r.page===`widget:upcoming-events`)return{blocks:[{type:`header`,text:`Upcoming events`},...((await Wt({},t)).events??[]).slice(0,5).map(e=>({type:`section`,block_id:`eventual-verbatim`,text:e.title+` · `+e.start}))]};let u=[{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 o=Vt((e.draftRevisionId?await t.content.getRevision?.(a.slug,e.id,e.draftRevisionId):void 0)?.data??e.data),c=new Set(a.fields.filter(e=>!e.validation?.relation).map(e=>e.slug)),l=await t.content.create(a.slug,Object.fromEntries(Object.entries({...o,title:String(o.title??`Event`)+` (copy)`}).filter(([e])=>c.has(e))),{locale:e.locale??void 0});u.push({type:`context`,text:`Draft copy created.`},{type:`actions`,elements:[s(l.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 d=await P(t);u.push({type:`actions`,elements:[s(`new`,`Create event`),o(c,`All events`),...[`venue`,`organizer_ref`].flatMap(e=>{let t=F(a,e);return d.some(e=>e.slug===t)?[o(`/_emdash/admin/content/`+encodeURIComponent(t),e===`venue`?`Manage venues`:`Manage organizers`)]:[]})]});let f=String(r.action_id).startsWith(`page-native-events`)?String(r.value||``):void 0,p=await t.content.list(a.slug,{limit:20,cursor:f});u.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:p.items.map(e=>({title:String(e.data.title||e.slug),locale:e.locale??``,status:e.status,edit:s(e.id,`Edit`),...n?{copy:{type:`button`,action_id:`duplicate-event`,label:`Duplicate`,value:e.id}}:{}})),empty_text:`No events yet.`}),p.hasMore&&(!p.cursor||p.cursor===f)&&i(`Incomplete event page. Reload the workspace.`);let m=[...f?[{type:`button`,action_id:`page-native-events-first`,label:`First page`,value:``}]:[],...p.hasMore?[{type:`button`,action_id:`page-native-events-next`,label:`Next events`,value:p.cursor}]:[]];return m.length&&u.push({type:`actions`,elements:m}),u.push({type:`header`,text:`Subscribe`},{type:`actions`,elements:[o(l+`calendar`,`Calendar subscription (.ics)`),o(l+`publicEvents`,`Published events (JSON)`)]}),{blocks:u}}const qt=e=>({type:`context`,text:e}),Jt=()=>({type:`actions`,elements:[[`/events`,`Events`],[`/settings`,`Settings`]].map(([e,t])=>({type:`button`,action_id:`open-page:`+e,label:t,value:e}))});async function Yt(e,t){let n=await Qe(e),r=await $e(e),i=await P(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)=>t.slug===n?.[e]||t.fields.some(t=>e===`events`?t.slug===`start`:[`name`,`title`].includes(t.slug)&&t.type===`string`),c=(e,t)=>({type:`select`,action_id:e,label:t,options:[{value:``,label:e===`events`?`Choose a collection`:`No collection`},...i.filter(t=>s(e,t)).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:[Jt(),{type:`header`,text:`Settings`},qt(i.some(e=>s(`events`,e))?`Choose content types.`:`Event collection needs start (datetime). Apply the event blueprint first.`),...t?[{type:`banner`,title:`Settings not saved`,description:t,variant:`error`}]:[],{type:`form`,block_id:`collection-settings:`+Object.values(n??{}).join(`:`),fields:[c(`events`,`Event collection`),c(`venues`,`Venue collection`),c(`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=L(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`}]};if(String(r.action_id??``).startsWith(`open-page:`)&&(r.type=`page_load`,r.page=r.value,delete r.action_id),r.page===`/settings`||r.action_id===`save-settings`||r.action_id===`save-legacy-reads`){if(!n||n.role<50)return{blocks:[Jt(),qt(`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 et(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 rt(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{if(!(await tt(t)).schema){let e=await $e(t);return{blocks:[Jt(),{type:`header`,text:`Connect events to a content type`},qt(`Choose an event content type.`),qt(e?`Public calendars show old plugin events.`:`Turn on "Show old events saved inside the plugin" in settings if needed.`),qt(`You can copy the old events into a content type. See the setup guide.`)]}}return{blocks:[Jt(),...(await Kt(r,t,n)).blocks]}}catch(e){return{blocks:[Jt(),{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
+ `;)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=L(e),r=await gn(n,_n,t,()=>ut(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=j([{...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?A(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=N(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=N(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=N(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=Ce(g,t,n).map(e=>{let t=e.id.slice(7),n=A(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?Oe(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:{};[...E.slice(1),E[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=>N(e.exceptions)??[],In=e=>N(e.occurrence_content)??[],V=e=>({type:`editor-draft-patch`,operations:e}),H=(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 I(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:N(o.recurrence),exceptions:N(o.exceptions),occurrence_content:N(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=Rt(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=V(t.rule?[H(`recurrence`,t.rule)]:[Ln(`recurrence`)])}else if(e===`apply-schedule`){let e=Vn(s);c=V([...Object.entries(e).map(([e,t])=>H(e,t)),...e.all_day?[Ln(`start`),Ln(`end`)]:[Ln(`start_date`),Ln(`end_date`)]])}else if(e===`apply-details`){let e=await I(t);for(let n of[`venue`,`organizer_ref`].filter(e=>Object.hasOwn(s,e))){e&&!e.fields.some(t=>t.slug===at(e,n))&&i(`Upgrade event reference schema first.`);let r=a(s[n]);r&&!await t.content?.get(F(e,n),r)&&i(`Selected entry no longer exists.`)}c=V([...[`venue`,`organizer_ref`].filter(e=>Object.hasOwn(s,e)).map(t=>H(at(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=Ie(o,{allowStaleOccurrenceCopy:!0}),r=A({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:N(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=V([H(`exceptions`,wn(Fn(o),u))])),e===`restore-occurrence`&&(c=V([H(`exceptions`,En(Fn(o),u))])),e===`clear-occurrence-copy`&&(c=V([H(`occurrence_content`,On(In(o),u))])),e===`reschedule-occurrence`){let e=Vn(s,`override_`);c=V([H(`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&&M(t)===a(s.copy_description)?t:Ee(a(s.copy_description))}let t=In(o).filter(e=>e.recurrenceId!==u);c=V([H(`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]))&&Ie(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??``)}),U=(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=zt(e.recurrence),a={...i,...n.values},o=i.frequency===`monthly`?i.monthlyPatternType===`weekdayOfMonth`?`monthly-weekday`:`monthly-day`:i.frequency,s=[...E.slice(1),E[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:Bt(e.recurrence)},Pn(`apply-recurrence`,`Save repeat settings`,c)],n.action===`apply-recurrence`));let l=await I(t),u=[];for(let[r,i]of[[`venue`,`Saved venue`],[`organizer_ref`,`Saved organizer`]]){let a=at(l,r);if(!l?.fields.some(e=>e.slug===a))continue;let o=F(l,r),s=it(e[a]),c=kn((await P(t)).some(e=>e.slug===o)?await B(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{Ie(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=k(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:[U(`edit-occurrence`,`Change date`,e.recurrenceId),...e.status===`cancelled`?[U(`restore-occurrence`,`Restore date`,e.recurrenceId)]:[U(`cancel-occurrence`,`Cancel date`,e.recurrenceId)],...e.status===`modified`?[U(`restore-occurrence`,`Restore date`,e.recurrenceId)]:[]]});let l=[];n.offset&&l.push(U(`page-occurrences-prev`,`Previous dates`,JSON.stringify({from:a,offset:Math.max(0,n.offset-20)}))),s.hasMore&&l.push(U(`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:[U(`window-prev`,`Previous 90 days`,k(a,-90)),U(`window-next`,`Next 90 days`,k(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`?M(i[e]):i[e],e===`description`),condition:{field:`use_`+e,eq:!0}}])]),{type:`actions`,elements:[U(`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=L(t);let n=await I(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,r={})=>e({status:t,headers:{"content-type":`text/plain; charset=utf-8`,"cache-control":`no-store`,...r},body:{kind:`text`,value:n}}),Qn=()=>Zn(404,`Not found`);async function $n(t,n){if(n=L(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 z(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 $e(n),l=o?Ue(s):c?await R(n,r)??await R(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||!ze(d.mimeType))return Qn();if(d.size!==null&&d.size>Re)return Zn(413,`Event image is too large`);try{let t=await n.media.readBytes(u,{maxBytes:Re});return!ze(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=>W(e,n))),s=new Map;for(let e of t){let t=W(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:${G(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
+ `)}\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:${Ne(e)}`,a=je(e),o=Me({...e,externalUrl:e.publicUrl||e.externalUrl}),s=M(e.description);return[`BEGIN:VEVENT`,`UID:${G(W(e,t))}`,`DTSTAMP:${sr(n)}`,`LAST-MODIFIED:${sr(r)}`,`SEQUENCE:${ar(e.calendarSequence,r)}`,i,`SUMMARY:${G(e.title)}`,...s?[`DESCRIPTION:${G(s)}`]:[],...a?[`LOCATION:${G(a)}`]:[],...o?[`URL:${o}`]:[],...e.categories.length?[`CATEGORIES:${e.categories.map(G).join(`,`)}`]:[],`X-EVENTUAL-TIMEZONE:${G(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:${G(W(e,t))}`,`DTSTAMP:${sr(n)}`,`LAST-MODIFIED:${sr(r)}`,`SEQUENCE:${ar(e.calendarSequence,r)}`,`STATUS:CANCELLED`,`SUMMARY:Cancelled event`,`X-EVENTUAL-TIMEZONE:${G(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 W(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 G(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=async e=>Array.from(new Uint8Array(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e))),e=>e.toString(16).padStart(2,`0`)).join(``),dr=`state:eventual-calendar-snapshot`,fr=new WeakMap;function pr(e,t=`eventual.invalid`){try{return new URL(e.site.url).host}catch{return t}}function mr(e,t=`eventual.invalid`){let n=fr.get(e);if(n)return n;let r=hr(e,t);return fr.set(e,r),r}async function hr(e,t){let n=await e.kv.get(dr);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=pr(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 gr(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(dr);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||=pr(e),fr.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=lt(e,1);try{let r=await Nt(e);if(!r.native)return{events:r.events,cancellations:[]};r.events=await Lt(e,r.events,!1);let s=await Pt(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:De(s,e)}))]),v=await ur(m),y=u.get(o),b=y?.fingerprint===v||y?.fingerprint===m;if(b&&y.from===n){y.fingerprint!==v&&(d.set(o,{...y,fingerprint:v}),f=!0),_+=y.occurrences.length,_>1e4&&i(`Calendar occurrence limit exceeded.`),g.push(...p.map(e=>({...e,calendarSequence:y.sequence}))),h.push(...y.cancellations),h.length>1e4&&i(`Calendar cancellation limit exceeded.`);continue}let ee=!b,S=y?y.sequence+(ee?1:0):p.some(e=>e.calendarUid)?Math.floor(t.getTime()/1e3):0;S>2147483647&&i(`Calendar sequence exhausted.`);let C=j(p.slice(0,1),n,a);C.length>1e3&&i(`Calendar occurrence limit exceeded.`),_+=C.length,_>1e4&&i(`Calendar occurrence limit exceeded.`);let w=new Set(C.map(e=>W(e,l))),T=new Map(C.map(e=>[W(e,l),e.categories.map(x)])),E=[...new Set(p.flatMap(e=>e.locale?[e.locale.toLowerCase()]:[]))],D=(y?.cancellations??[]).filter(e=>Date.parse(e.cancelledAt)>t.getTime()-366*864e5&&(e.feedCategory?!T.get(W(e,l))?.includes(e.feedCategory):e.locale?!E.includes(e.locale):!w.has(W(e,l))));for(let e of y?.occurrences??[])if(!w.has(W(e,l))&&e.end.slice(0,10)>=n&&D.push({...e,cancelledAt:t.toISOString(),calendarSequence:S}),w.has(W(e,l)))for(let n of e.categories??[])T.get(W(e,l))?.includes(x(n))||D.push({...e,feedCategory:x(n),cancelledAt:t.toISOString(),calendarSequence:S});for(let e of y?.locales??[])if(!E.includes(e))for(let n of y?.occurrences??[])w.has(W(n,l))&&D.push({...n,locale:e,cancelledAt:t.toISOString(),calendarSequence:S});let te=[...new Map(D.map(e=>[W(e,l)+`:`+(e.locale??``)+`:`+(e.feedCategory??``),e])).values()];te.length>1e3&&i(`Cancellation history limit exceeded for this series.`);let ne={from:n,locales:E,fingerprint:v,sequence:S,occurrences:C.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:S,cancelledAt:t.toISOString(),categories:e.categories,locales:E})),cancellations:te};d.set(o,ne),f=!0,g.push(...p.map(e=>({...e,calendarSequence:S}))),h.push(...te),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(dr,o?.revision??null,v)).applied||i(`Calendar state conflict; retry.`)),{events:g,cancellations:h,venues:s,host:l}}finally{p()}}async function _r(e,t,n){e=L(e,30);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 z(e),c=s?{native:!0,schema:s,events:[]}:await Nt(e,o),l=c.native?await gr(e):{events:c.events,cancellations:[]},u=n?.eventId,d=u?.split(`#`)[0],f=j(It(d?l.events.filter(e=>e.id===d):l.events,n?.locale,n?.strict),r,o),p=u?.includes(`#`)?f.filter(e=>e.id===u):f;p.length>1e4&&i(`Too many calendar occurrences.`);let m=n?.category?x(n.category):``,h=m?p.filter(e=>e.categories.some(e=>x(e)===m)):p;if(u&&!h.length)return``;let g=`venues`in l&&l.venues||await Pt(e,h,c.schema),_=(c.native?await Lt(e,h):h).map(e=>({...e,location:We(e,g).location})),v=!u&&e.storage?.calendar_cancellations?await St(e):[];return er(_,u?[]:[...l.cancellations,...v].filter(e=>Date.parse(e.cancelledAt)>Date.now()-366*864e5&&(!m||e.categories?.some(e=>x(e)===m))&&(!e.feedCategory||e.feedCategory===m)&&(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 mr(e,t),void 0,n?.calendarName)}const K=(e,t)=>({type:`object`,properties:e,...t&&t.length>0?{required:t}:{},additionalProperties:!1}),q=(e=0,t=12e3)=>({type:`string`,...e>0?{minLength:e}:{},maxLength:t}),J={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:[K({frequency:{type:`string`,const:`daily`},until:J,interval:Y(1,52)},[`frequency`,`until`]),K({frequency:{type:`string`,const:`weekly`},until:J,interval:Y(1,52),weekdays:yr(br,7,1)},[`frequency`,`until`]),K({frequency:{type:`string`,const:`monthly`},until:J,interval:Y(1,52),pattern:{oneOf:[K({type:{type:`string`,const:`dayOfMonth`},dayOfMonth:Y(1,31),missingDayBehavior:X([`skip`,`lastDay`])},[`type`,`dayOfMonth`,`missingDayBehavior`]),K({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(q(0,100),30),Tr={title:q(1,200),description:q(0,12e3),start:q(1,32),end:q(1,32),allDay:vr,timezone:q(1,100),location:q(0,500),locationType:Sr,virtualUrl:q(0,2048),status:Cr,organizer:q(0,300),organizerId:q(0,200),externalUrl:q(0,2048),imageUrl:q(0,2048),imageMediaId:q(0,200),categories:wr,venueId:q(0,200),recurrence:xr},Er=K({id:q(1,200)},[`id`]),Dr=K(Tr,[`title`,`start`,`end`,`allDay`]),Or=K({...Tr,recurrence:{anyOf:[xr,{type:`null`}]}}),kr={name:q(1,200),street:q(0,300),street2:q(0,300),locality:q(0,150),region:q(0,150),postalCode:q(0,40),country:q(0,100)},Ar=K(kr,[`name`]),jr=K({id:q(1,200)},[`id`]),Mr=K(kr),Nr=K({id:q(1,200),patch:Or},[`id`,`patch`]),Pr=K({id:q(1,200),patch:Mr},[`id`,`patch`]),Fr=K({locationType:Sr,virtualUrl:q(0,2048),status:Cr,title:q(1,200),description:q(0,12e3),start:q(1,32),end:q(1,32),allDay:vr,timezone:q(1,100),location:q(0,500),organizer:q(0,300),externalUrl:q(0,2048),imageUrl:q(0,2048),categories:wr}),Ir=K({eventId:q(1,200),recurrenceId:q(0,16),status:X([`cancelled`,`modified`]),overrides:Fr},[`eventId`,`recurrenceId`,`status`]),Lr=K({eventId:q(1,200),recurrenceId:q(0,16)},[`eventId`,`recurrenceId`]),Rr=K({}),zr=K({from:J,through:J,includeDrafts:vr,limit:Y(1,100)}),Br=K({id:q(1,200),from:J,through:J,limit:Y(1,100)},[`id`]),Vr=K({defaultTimezone:q(1,100),collections:K({events:q(1,63),venues:q(0,63),organizers:q(0,63)},[`events`,`venues`,`organizers`]),legacyReads:vr},[`defaultTimezone`]),Hr={name:q(1,200),website:q(0,2048),contactUrl:q(0,2048)},Ur=K(Hr,[`name`]),Wr=K({id:q(1,200),expectedUpdatedAt:q(1,32),patch:K(Hr)},[`id`,`expectedUpdatedAt`,`patch`]),Gr={id:q(1,200),createdAt:q(1,32),updatedAt:q(1,32)},Kr=K({start:q(1,32),end:q(1,32),allDay:vr,timezone:q(1,100),changedAt:q(1,32)},[`start`,`end`,`allDay`,`timezone`,`changedAt`]),qr=K({recurrenceId:q(1,16),status:X([`cancelled`,`modified`]),overrides:K({...Fr.properties,imageMediaId:q(0,200)})},[`recurrenceId`,`status`]),Jr={events:K({...Tr,...Gr,calendarSequence:Y(0,2147483647),calendarUid:q(1,500),locale:q(1,40),translations:{type:`object`,maxProperties:20,additionalProperties:K({title:q(1,500),description:q(0,1e4),location:q(0,500),organizer:q(0,500)},[`title`,`description`,`location`,`organizer`])},published:vr,exceptions:yr(qr,500),scheduleHistory:yr(Kr,10),previousStartDate:q(1,32)},[`id`,`title`,`description`,`start`,`end`,`allDay`,`timezone`,`location`,`organizer`,`externalUrl`,`imageUrl`,`categories`,`published`,`exceptions`,`createdAt`,`updatedAt`]),venues:K({...kr,...Gr},Object.keys({...kr,...Gr})),organizers:K({...Hr,...Gr},Object.keys({...Hr,...Gr}))},Yr=K({collection:X([`events`,`venues`,`organizers`]),source:q(1,200),mode:X([`copy`,`restore`]),records:yr(K({sourceId:q(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:K({collection:X([`events`,`venues`,`organizers`]),cursor:q(1,2e3),limit:Y(1,10)},[`collection`]),migrateToNative:K({locale:q(1,20),venueCollection:q(1,100),dryRun:vr,cursor:q(1,4e3),limit:Y(1,100),venueMapping:{type:`object`,additionalProperties:q(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&&!D(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||!ze(n.mimeType))return!1;if(n.size!==null)return n.size<=Re;if(!e.media?.readBytes)return!1;try{let r=await e.media.readBytes(t,{maxBytes:Re});return r.mimeType===n.mimeType&&ze(r.mimeType)&&r.bytes.byteLength<=Re}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&&!T(e)))return{ok:!1,error:`Use a name and valid public HTTP(S) URLs.`};let a=At(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=vt(o?.value.updatedAt),c={...i,website:T(i.website),contactUrl:T(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=L(i)),Qr(e,r.input)?!n&&await z(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?de(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=ue(i);if(!a.data)return $(a.error??`Check the event fields.`);if(a.data.externalUrl&&!T(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 Ct(e,i.venueId))return $(`The selected saved venue does not exist.`);if(i.organizerId&&!await At(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 we(s)?{ok:!0,event:await _t(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 z(t);if(n){let e=F(n,`organizer_ref`);return(await P(t)).some(t=>t.slug===e)?{ok:!0,organizers:(await B(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 jt(t)}},!0),"mcp/organizers/create":Q(`createOrganizer`,async(e,t)=>ni(t,e)),"mcp/organizers/update":Q(`updateOrganizer`,async(e,t)=>{let n=await At(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 z(t);if(a){let n=(await B(t,a.slug)).map(Ue).filter(e=>e!==null);return{ok:!0,from:r,through:i,events:j(e.includeDrafts?n:n.filter(e=>e.published),r,i).slice(0,e.limit??50)}}let o;try{o=await Dt(t,{published:e.includeDrafts?void 0:!0})}catch(e){if(e instanceof pt)return{ok:!1,error:`EVENT_LIMIT_EXCEEDED`,maxEvents:e.limit};throw e}let s=j(o,r,i).slice(0,e.limit??50),c=await kt(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 z(t);if(n){let r=await t.content?.get(n.slug,e);if(!r)return Z();let i=Ue(r);if(!i)return Z();let a=await z(t),o=await Pt(t,[i],a);return{ok:!0,event:(await Lt(t,[i]))[0],venue:De(o,i)??null}}let r=await R(t,e);return r?{ok:!0,event:r,venue:r.venueId?await Ct(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 z(t);if(i){let a=await t.content?.get(i.slug,e.id);if(!a)return Z();let o=Ue(a);return o?{ok:!0,eventId:o.id,published:o.published,...Sn(o,n,r,e.limit??50)}:Z()}let a=await R(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 R(n,e);if(!r)return Z();let i=de(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 R(t,e);if(!n)return Z();let r={...n,published:!0,status:le(!0,n.status),updatedAt:new Date().toISOString()};return await _t(t,r),{ok:!0,event:r}}),"mcp/events/unpublish":Q(`getEvent`,async({id:e},t)=>{let n=await R(t,e);if(!n)return Z();let r={...n,published:!1,status:le(!1,n.status),updatedAt:new Date().toISOString()};return await _t(t,r),{ok:!0,event:r}}),"mcp/events/delete":Q(`getEvent`,async({id:e},t)=>({ok:!0,deleted:await bt(t,e)})),"mcp/events/exception/set":Q(`setOccurrenceException`,async(e,t)=>{let n=await R(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(!A(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&&!T(t.virtualUrl))return $(`Virtual URL must use HTTP or HTTPS.`);if(t.virtualUrl!==void 0&&(l.virtualUrl=T(t.virtualUrl)),t.status!==void 0&&(l.status=le(n.published,t.status)),t.externalUrl!==void 0&&t.externalUrl&&!T(t.externalUrl))return $(r);if(t.imageUrl!==void 0&&t.imageUrl&&!T(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 _t(t,s),{ok:!0,event:s}}),"mcp/events/exception/remove":Q(`removeOccurrenceException`,async({eventId:e,recurrenceId:t},n)=>{let r=await R(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 _t(n,a),{ok:!0,event:a}}),"mcp/venues/list":Q(`getSettings`,async(e,t)=>{let n=await z(t);return n?{ok:!0,venues:(await B(t,F(n,`venue`))).map(Oe).filter(Boolean)}:{ok:!0,venues:await Ot(t)}},!0),"mcp/venues/create":Q(`createVenue`,async(e,t)=>{let n=ai(e);return await wt(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 Ct(n,e);if(!r)return Z();let i=ai({...r,...t},r);return await wt(n,i),{ok:!0,venue:i}}),"mcp/venues/delete":Q(`getEvent`,async({id:e},t)=>await Ct(t,e)?await Et(t,e)?{ok:!1,error:`VENUE_IN_USE`}:{ok:!0,deleted:await Tt(t,e)}:Z()),"mcp/settings/get":Q(`getSettings`,async(e,t)=>({ok:!0,defaultTimezone:await t.settings.get(`defaultTimezone`)??`UTC`,collections:await Qe(t)??null,legacyReads:await $e(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 rt(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 et(r,n),await r.settings.set(`defaultTimezone`,e),{ok:!0,defaultTimezone:e,legacyReads:await $e(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 P(e),u=await I(e);u||i(`Apply the event blueprint before migrating.`);let d=F(u,`venue`),f=at(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 B(e,o.venueCollection),h=await B(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 ee=r?pr(e):await mr(e),S=await e.kv.get(`state:eventual-calendar-host`),C=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))},w=async(t,a,o,s,c)=>{await C();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 C(),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 C(),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}]:[]}),C=b.filter(e=>e.status===`cancelled`||Object.keys(e.overrides??{}).length),w=l.organizerId?await e.storage.organizers?.get(l.organizerId):void 0,T=Ie({start:l.start,end:l.end,all_day:l.allDay,timezone:l.timezone,recurrence:l.recurrence,exceptions:C,occurrence_content:x});n=ci(m,{title:c,description:Ee(a(l.description)),excerpt:M(l.description).slice(0,160),...T,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:w?JSON.stringify(w):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(C),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:W(t,S??ee),legacy_metadata:JSON.stringify({createdAt:l.createdAt,updatedAt:l.updatedAt,organizerId:l.organizerId,locale:l.locale,description:l.description,exceptions:l.exceptions})}),Ue({id:t,status:`published`,type:`events`,data:n})||i(`Invalid migrated event payload.`),d=l.published===!0}let g=await w(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 gr(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){return`import-${await ur(JSON.stringify([e,t,n]))}`}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&&!T(e))&&i(`Public URLs must use HTTP(S).`),{...n,name:e.name.trim(),id:r,updatedAt:s}}let c=n;(!fi(c)||c.recurrence&&!D(c.recurrence))&&i(`Invalid schedule or recurrence.`);let l=ue(de({...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=A(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&&!T(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||!we(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=L(e),await z(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?ut(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 z(t);if(r){let e=n.collection===`venues`?F(r,`venue`):n.collection===`organizers`?F(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=L(t),e.collection===await Ze(t)){if(!Fe.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=Ie({...n,...e.content},{allowStaleOccurrenceCopy:!Object.hasOwn(e.content,`occurrence_content`)||JSON.stringify(N(e.content.occurrence_content)??[])===JSON.stringify(N(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 P(t)).find(t=>t.slug===e.collection),a=e=>n?.fields.some(t=>t.slug===e),s=N(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&&=L(t),e.collection===(t?await Ze(t):`events`))try{let n=e.content.data&&typeof e.content.data==`object`?e.content.data:e.content;if(Ie(n,{allowStaleOccurrenceCopy:!0}),t&&(n.venue_id??n.venue)){let e=F(await I(t),`venue`),r=it(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=it(n.organizer_id??n.organizer_ref??n.organizerId);if(e){let n=F(await I(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 Qe(n);if(r&&![r.venues,r.organizers].includes(e))return;let a=await I(n);if(!a)return;let o=F(a,`venue`),s=F(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 B(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(it(t.venue_id??t.venue)??``)||e===s&&l.has(it(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=L(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=L(t),e.collection===await Ze(t)){await gr(t);return}if(await vi(e.collection,e.id,t))return!1}const xi=(e,t)=>{let n=new URL(t).origin;try{return e&&new URL(e).host===new URL(n).host?e:n}catch{return n}},Si=e=>Zn(503,e.message,{"retry-after":`60`});async function Ci(e,t,n){let r=L(e),i=await n(r),a=await vn(r,t);return a?$t(i,a):i}const wi={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)=>Ci(t,e.ui?.locale,t=>Xt(e.input,{...t,site:{...t.site,url:xi(t.site.url,e.request.url)}},e.user))},"admin/editor/schedule":{permission:`content:edit_any`,handler:async(e,t)=>Ci(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 Wt(e.input,t);if(n.error===`SANDBOX_BUDGET_EXCEEDED`)throw new ot;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 ot)return Si(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 Zn(400,`Invalid locale.`)}let a=r.searchParams.get(`strict`)===`true`,o=r.searchParams.get(`category`)||void 0,s=r.searchParams.get(`eventId`)?.trim()||void 0,c=await _r(n,r.host||`localhost`,{locale:i,strict:a,category:o,eventId:s});return c?e({status:200,headers:{"content-type":`text/calendar; charset=utf-8`},body:{kind:`text`,value:c}}):Zn(404,`This event has ended or is no longer published.`)}catch(e){return Si(e instanceof pt||e instanceof ot?e:Error(`Calendar feed unavailable; retry later.`))}}})}};export{wi as default};